代码如下:
<?php
verify();
function verify($width=100,$height=40,$num=5,$type=3)
{
$image = imagecreatetruecolor($width,$height);
imagefill($image,0,0,lightColor($image));
$string = '';
switch($type){
case 1:
$str = '0123456789';
$string = substr(str_shuffle($str),0,$num);
break;
case 2:
$arr = range('a','z');
shuffle($arr);
$tmp = array_slice($arr,0,5);
$string = join('',$tmp);
break;
case 3:
$str = '0123456789qwertyuiopasdfghjlkzxcvbnm
ASDFGHJKLQWERTYUIOPZXCVBNM';
$string = substr(str_shuffle($str),0,$num);
break;
}
for($i=0;$i<$num;$i++){
$x = floor($width/$num)*$i;
$y = mt_rand(10,$height-20);
imagechar($image,5,$x,$y,$string[$i],deepColor($image));
}
for($i=0;$i<$num;$i++){
imagearc($image,mt_rand(10,$width),
mt_rand(10,$height),mt_rand(10,$width),mt_rand(10,$height),
mt_rand(0,10),mt_rand(0,270),deepColor($image));
}
for($i=0;$i<50;$i++){
imagesetpixel($image,mt_rand(0,$width),
mt_rand(0,$height),deepColor($image));
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
}
function lightColor($image){
return imagecolorallocate($image,mt_rand(130,255),
mt_rand(130,255),mt_rand(130,255));
}
function deepColor($image){
return imagecolorallocate($image,mt_rand(0,120),
mt_rand(0,120),mt_rand(0,120));
}
?>
用到的字符串函数和数组函数: str_shuffle函数可以打乱字符串的顺序,substr函数截取字符串。 shuffle函数打乱数组顺序,array_slice截取数组,join将数组连接为字符串。
用到的GD库函数: imagefill用来填充画布背景色。
imagefilledrectangle函数跟上面函数的用法相似。
imagechar函数用来在图上写字。
imagesetpixel函数用来画干扰点。imagearc函数用来画干扰线。
最终生成的随机验证码效果图如下: