使用PHP製作驗證碼
阿新 • • 發佈:2019-01-23
製作驗證碼的幾個步驟:
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();
}