php中GD扩展库可以对图像进行处理,php验证码的实现是生成随机码并保存到session,最后生成图片的过程。随机码保存到session后,服务端会把随机码保存到服务器的文件中,并生成一个cookie,然后下发到客户端保存,并通过cookie进行和服务端关联,来达到客户端和服务端进行验证的目的。
图像处理函数列表:http://www.php.net/manual/zh/ref.image.php
checkcode.php
设置变量
$captcha_code = "";
//随机种子
$char_str = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
$char_str_len = strlen($char_str)-1;
$checkcode = $code = '';
//生成随机码
for($i=0;$i<4;$i++){
//设置字体大小
$fontsize = 6;
//设置字体颜色,随机颜色
$fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120));
//设置数字
$code = substr($char_str,rand(0,$char_str_len),1);
//拼接验证码
$checkcode .= $code;
//随机码宽度
$x = ($i*$w/4)+rand(5,10);
//随机码高度
$y = rand(5,$h/2);
imagestring($image,$fontsize,$x,$y,$code,$fontcolor);
}
//保存code到session
$_SESSION['checkcode'] = $checkcode;
//设置雪花点
for($i=0;$i<400;$i++){
//设置点的颜色
$pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200));
//imagesetpixel画一个单一像素
imagesetpixel($image, rand(0,$w), rand(0,$h), $pointcolor);
}
//增加干扰元素
for($i=0;$i<4;$i++){
//设置线的颜色
$linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220));
//设置线,两点一线
imageline($image,rand(1,$w-1), rand(1,$h-1),rand(1,$w-1), rand(1,$h-1),$linecolor);
}
//设置图片头部
header('Content-Type: image/png');
//生成png图片
imagepng($image);
//销毁$image
imagedestroy($image);check.html
登陆
效果:
服务端验证代码login.php:



