制作验证码的几个步骤:
1.绘制验证码图片
2.将验证码保存到服务器
3.检验用户提交的验证码是否正确
1.绘制验证码:
$image = imagecreatetruecolor(100,30);//建立一个宽100,高30的画布,且默认背景为黑色
$color = imagecolorallocate($image, 255, 255, 255);// 为一幅图像分配颜色,后三个参数为RGB值
imagefill($image, 0, 0, $color);//将刚才设置的颜色,白色,填充到画布中
for($i = 0; $i < 4; $i++){//验证码的四个数字或字母
$size = 6;
$color = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
$data = 'qwertyupasdfghjkzxcvbnm3456789';
$content = substr($data,rand(0,strlen($data)),1);
$x = ($i * 100 / 4 ) + rand(5,10);
$y = rand(5,15);
imagestring($image, $size, $x, $y, $content, $color);//水平地画一行字符串,$x,$y分别为横坐标和纵坐标
}
for($i = 0; $i < 300; $i++){//向画布中添加点增加干扰
$color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
imagesetpixel($image, rand(1,99), rand(1,29), $color);//画一个单一像素
}
for($i = 0; $i < 3; $i++){//向画布中添加线增加干扰
$color = imagecolorallocate($image, rand(80,220), rand(80,220), rand(80,220));
imageline($image, rand(1,99), rand(1,29), rand(1,99), rand(1,29), $color);// 画一条线段
}
header("Content-type:image/png");//表示输出的是图片类型
imagepng($image);
imagedestroy($image);
第一步绘制验证码就这样完成了。
2.将验证码保存在服务器中:
使用了session
session_start();
$image = imagecreatetruecolor(100,30);
$color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $color);
$code='';
for($i = 0; $i < 4; $i++){
$size = 6;
$color = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
$data = 'qwertyupasdfghjkzxcvbnm3456789';
$content = substr($data,rand(0,strlen($data)),1);
$code .= $content;
$x = ($i * 100 / 4 ) + rand(5,10);
$y = rand(5,15);
imagestring($image, $size, $x, $y, $content, $color);
}
$_SESSION['code'] = $code;
for($i = 0; $i < 300; $i++){
$color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
imagesetpixel($image, rand(1,99), rand(1,29), $color);
}
for($i = 0; $i < 3; $i++){
$color = imagecolorallocate($image, rand(80,220), rand(80,220), rand(80,220));
imageline($image, rand(1,99), rand(1,29), rand(1,99), rand(1,29), $color);
}
header("Content-type:image/png");
imagepng($image);
imagedestroy($image);
3.验证:
if(isset($_REQUEST['authcode'])){
session_start();
if(strtolower($_REQUEST['authcode']) == $_SESSION['authcode']){
echo "<script>alert('输入正确');window.location.href='form.php';</script>";
}else{
echo "<script>alert('输入错误');window.location.href='form.php';</script>";
}
exit();
}