0x01 验证码字符的生成
新建一个codei.php(图像输出为png格式)
用dechex()将数字转换成十六进位制(包含字母)
用session保存可以跨文件调用。
session_start();
for($i = 0;$i < 4;$i++){
if(!isset($_n)){
$_n = '';
}
$_n.= dechex(mt_rand(0,15));
}
$_SESSION['code'] = $_n;
0x02 图像的绘制
简单粗暴的全部复制粘贴了。。。
注意里面有一个验证码排布的公式
$width = 100;
$height = 30;
$code = imagecreatetruecolor($width,$height);
header('Content-Type:image/png');
$white = imagecolorallocate($code,255,255,255);
$black = imagecolorallocate($code,0,0,0);
imagefill($code,0,0,$white); //填充背景色;
imagerectangle($code,0,0,$width - 1,$height - 1,$black); //描绘黑色边线
for($i = 0;$i < 6;$i++){
$rand_color = imagecolorallocate($code,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); //创建随机色
imageline($code,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$rand_color);//画出干扰线
}
for($i = 0;$i < 50;$i++){ //加入噪点
$rand_color2 = imagecolorallocate($code,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagestring($code,1,mt_rand(1,$width),mt_rand(1,$height),'.',$rand_color2);
}
for($i = 0;$i < strlen($_SESSION['code']);$i++){ //将文字加入图片
$rand_color3 = imagecolorallocate($code,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagestring($code,mt_rand(3,5),$i * $width / 4 + mt_rand(1,$width/4),mt_rand(1,$height/2),$_SESSION['code'][$i],$rand_color3);
}
imagepng($code); //输出图像
imagedestroy($code); //销毁
0x03 单击验证码局部刷新
新建一个code_index文件
<img src="code.php" οnclick="javascript:this.src='code.php?tm='+Math.random()"/>
重点是后面的JS代码,控制该区域的局部更新。