重要:
編寫本文代碼之前必須确定PHP伺服器已開啟GD庫,否則會報錯或無法正常工作;
輸出驗證碼代碼:
<?php
//開啟session支援
session_start();
// 生成驗證碼的底圖
$image = imagecreatetruecolor(, );
$bgcolor = imagecolorallocate($image, , , );
imagefill($image, , , $bgcolor);
// 輸出随機數字0-9字母A-Za-z字元
$captch_code = "";
for ($i=; $i<; $i++){
$fontsize = ;
$fontcolor = imagecolorallocate($image, rand(, ), rand(, ), rand(, ));
$data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$fontcontent = substr($data, rand(, strlen($data)), );
$captch_code .= $fontcontent;
$x = ($i*150/) + rand(, );
$y = rand(, );
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
// 儲存驗證碼
$_SESSION['authcode'] = $captch_code;
// 輸出幹擾點
for ($i=; $i<; $i++){
$color = imagecolorallocate($image, rand(, ), rand(, ), rand(, ));
imagesetpixel($image, rand(, ), rand(, ), $color);
}
// 輸出幹擾線
for ($i=; $i<; $i++){
$color = imagecolorallocate($image, rand(, ), rand(, ), rand(, ));
imageline($image, rand(, ), rand(, ), rand(, ), rand(, ), $color);
}
// 顯示圖檔
header("content-type: image/png");
imagepng($image);
// 關閉資源
imagedestroy($image);
?>
校驗驗證碼:
隻需要擷取使用者傳遞的驗證碼字元跟session中存儲的字元串相對比即可(實際運用中,如果有字母的話則需要将使用者所填寫的字母和伺服器的字母轉換成同一大寫或小寫,因為我們無法知道使用者是輸入大寫還是小寫)