php 用GD库来写验证码 GD库的很多函数 要有一个基本理解
/*4个步骤贯穿整个验证码的逻辑
1,底图的实现 添加干扰元素
2,生成验证内容
3,验证内容保存在服务端
4,验证内容的效验*/
session_start(); // 开启session 为存储验证码做准备
//画布
$image = imagecreatetruecolor(100, 30); // 创建一个宽100 高30的画布
$bgcolor = imagecolorallocate($image, 255, 255, 255); // 为这个画布分配颜色
imagefill($image, 0, 0, $bgcolor); // 把分配的颜色填充到画布里面
$captch_code = '';
//数字字母组合 来写验证码
for ($i=0; $i <4; $i++) {
$fontsize = 8; // 设置字体大小
$fontcolor = imagecolorallocate($image, rand(0,80), rand(0,80), rand(0,80));// 给验证码分配颜色
$data = 'abcdefghijkmnpqrstuvwxy3456789';// 验证码
$fontcontent = substr($data, rand(0,strlen($data)),1); // 计算出来验证码
$captch_code .= $fontcontent;
$x = ($i*100/4) + rand(5,10); // X坐标
$y = rand(5,10); // Y坐标
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); // 水平的画一行字符串 即上面得到的验证码
}
$_SESSION['authcode'] = $captch_code; // 把得到的验证码存放在session中
//干扰点
for ($i=0; $i <300 ; $i++) {
// 最多三百个点
$pointcolor = imagecolorallocate($image, rand(80,220), rand(80,220), rand(80,220)); //分配颜色
imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor); // 画单一像素
}
//干扰线
for ($i=0; $i <3 ; $i++) {
$linecolor = imagecolorallocate($image, rand(120,220), rand(120,220), rand(120,220)); // 同干扰点一样
imageline($image, rand(1,99), rand(1,29), rand(1,99), rand(1,29), $linecolor);// 画一条线段
}
header('content-type: image/png'); // 设置图片格式的访问头
imagepng( $image ); // 打印出图片
imagedestroy( $image ); // 销毁图片