驗證碼核心:GD 庫生成干擾圖片 + Session 存儲驗證值 + 表單提交比對。本例演示 4 位純數字驗證碼。
authpage.php:主頁,顯示表單與驗證碼圖片,處理提交驗證。authimg.php:動態生成驗證碼圖片並寫入 Session。<?php
session_start();
$authnum = $_SESSION['authnum'] ?? '';
if (isset($_POST['authinput'])) {
if (strcmp($_POST['authinput'], $_SESSION['authnum']) === 0) {
echo "驗證成功!";
} else {
echo "驗證失敗!";
}
}
?>
<form action="authpage.php" method="post">
<table>
<tr><td>請輸入驗證碼:<input type="text" name="authinput"></td></tr>
<tr><td><input type="submit" name="驗證" value="提交驗證碼"></td></tr>
<tr><td><img src="authimg.php" alt="驗證碼"></td></tr>
</table>
</form>
<?php
header("Content-type: image/PNG");
session_start();
$im = imagecreate(62, 20); // 創建畫布
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$gray = imagecolorallocate($im, 200, 200, 200);
imagefill($im, 0, 0, $gray); // 背景填充
// 生成 4 位隨機數
srand((double)microtime() * 1000000);
while (($authnum = rand() % 10000) < 1000); // 確保 4 位
$_SESSION['authnum'] = $authnum;
// 繪製數字
imagestring($im, 5, 10, 3, $authnum, $black);
// 添加干擾像素
for ($i = 0; $i < 200; $i++) {
$randcolor = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($im, rand()%70, rand()%30, $randcolor);
}
imagepng($im);
imagedestroy($im);
?>
session_start(),確保同一會話。srand((double)microtime()*1000000) 增加熵(PHP 4.2+ 可省略)。header("Content-type: image/PNG") 告知瀏覽器圖片類型。imagefttext 支持 TrueType 字體渲染更美觀。數字驗證碼是 PHP GD 庫入門最佳實踐,掌握畫布創建、顏色分配、字符串繪製、像素操作、Session 交互五大核心技能,即可靈活構建各類驗證碼系統。