製作驗證碼的幾個步驟:
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();
}