PHP采用GD绘制验证码

<?php
session_start();
vCode(5, 50); //5个数字,显示大小为50

function vCode($num = 5, $size = 20, $width = 0, $height = 0) {
!$width && $width = $num * $size * 4 / 5 + 5;
!$height && $height = $size + 10;
// 画图像
$im = imagecreatetruecolor($width, $height);
// 定义要用到的颜色
$back_color = imagecolorallocate($im, 235, 236, 237);
$boer_color = imagecolorallocate($im, 118, 151, 199);
$text_color = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));

// 画背景
imagefilledrectangle($im, 0, 0, $width, $height, $back_color);
// 画边框
imagerectangle($im, 0, 0, $width-1, $height-1, $boer_color);
// 画干扰线
for($i = 0;$i < 7;$i++) {
$font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(- $width, $width), mt_rand(- $height, $height), mt_rand(30, $width * 2), mt_rand(20, $height * 2), mt_rand(0, 360), mt_rand(0, 360), $font_color);
}
// 画干扰点
for($i = 0;$i < 70;$i++) {
$font_color = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $font_color);
}
// 去掉了 0 1 O l 等
$str = “23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW”;
$code = ”;
// 画验证码
for ($i = 0; $i < $num; $i++) {
$fontcont=$str[mt_rand(0, strlen($str)-1)];
$code .= $fontcont;
$x=$i*$size * 4 / 5 + 5;
$y=rand($height/4,$height/2);
imagestring($im,5,$x,$y,$fontcont,$text_color);
}
$_SESSION[“VerifyCode”]=$code;
header(“Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate”);
header(“Content-type: image/png;charset=utf-8”);
imagepng($im);
imagedestroy($im);
}

?>

魔术方法 __toString()与__autoload()

1.__toString()

该方法用于echo或print一个对象时,将对象转为字符串.

测试用例:

<?php
class toStringObject
{
private $type=”toString Test.”;
/*public function __toString()
{
return $this->type;
}
*/
}
$toString = new toStringObject();
echo $toString;
?>

返回为:

Catchable fatal error: Object of class toStringObject could not be converted to string in C:\xampp\htdocs\toString.php on line 12

直接输出对象会发生致命错误.

将注释掉的__toString()方法取消注释,返回为:

toString Test.

这样可以自定义输出一个对象时要返回的字符串.

2.__autoload() 

该方法用于自动加载要引用或包含的类文件,而不必每次都要include_once()或require_once().

要求:类名必须与包含该类的php文件名保持一致

优点:当需要引入很多类时,不必一个一个引入.

测试用例:

test.php

<?php
function __autoload($class_name)
{
$class_path = ‘./’.$class_name.’.php’;
if(file_exists($class_path)) include_once($class_path);
else die(“Not found this Class”);
}
$sport = new sportClass(iconv(“gbk”,”utf-8″,”你好”));
echo $sport;
?>

sportClass.php

<?php
class sportClass
{
private $cont;
public function __construct($cont)
{
$this->cont=$cont;
}
public function __toString()
{
RETURN $this->cont;
}
}
?>

返回为:

你好