提供一組完整可執行的 PHP 圖形驗證碼範例,包含驗證邏輯頁面(authpage.php)與動態生成圖片腳本(authimg.php)。驗證碼為四位數字,干擾像素增加辨識難度。
<?php
srand((double)microtime() * 1000000);
if (isset($_POST['authinput'])) {
if (strcmp($_POST['authnum'], $_POST['authinput']) == 0)
echo "驗證成功!";
else
echo "驗證失敗!";
}
// 產生 1000-9999 四位數
while (($authnum = rand() % 10000) < 1000);
?>
<form action="authpage.php" method="post">
<table>
請輸入驗證碼:<input type="text" name="authinput" style="width:80px"><br>
<input type="submit" name="驗證" value="提交驗證碼">
<input type="hidden" name="authnum" value="<?php echo $authnum; ?>">
<img src="authimg.php?authnum=<?php echo $authnum; ?>">
</table>
</form>
<?php
header("Content-type: image/PNG");
srand((double)microtime() * 1000000);
$im = imagecreate(58, 28);
$black = ImageColorAllocate($im, 0, 0, 0);
$white = ImageColorAllocate($im, 255, 255, 255);
$gray = ImageColorAllocate($im, 200, 200, 200);
imagefill($im, 68, 30, $gray);
imagestring($im, 5, 10, 8, $_GET['authnum'], $white);
// 加入 50 個干擾像素
for ($i = 0; $i < 50; $i++) {
imagesetpixel($im, rand() % 70, rand() % 30, $gray);
}
ImagePNG($im);
ImageDestroy($im);
?>
imagettftext())替換內建字體,提升美觀與辨識度。random_int() 取代 rand()。