本文提供一套基於 PHP GD 庫的四位數字驗證碼完整實現,包含驗證碼生成、圖片輸出、干擾像素、Session 存儲與表單驗證邏輯,代碼經調試可直接運行,適合快速集成至舊項目或教學參考。
authpage.php:主頁面,生成驗證碼、輸出表單、驗證用戶輸入。authimg.php:驗證碼圖片生成腳本,輸出 PNG 圖片流。<?php
session_start(); // 必須啟用 Session
// 1. 處理表單提交驗證
if (isset($_POST['authinput'])) {
if (strcmp($_SESSION['authnum'], $_POST['authinput']) === 0) {
echo "驗證成功!";
} else {
echo "驗證失敗!";
}
}
// 2. 生成新的四位數字驗證碼存入 Session
$_SESSION['authnum'] = sprintf('%04d', mt_rand(0, 9999)); // 確保四位,含前導零
?>
<form action="authpage.php" method="post">
<table>
<tr>
<td>請輸入驗證碼:</td>
<td><input type="text" name="authinput" style="width:80px"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="提交驗證"></td>
</tr>
<tr>
<td></td>
<td><img src="authimg.php" alt="點擊刷新" style="cursor:pointer;vertical-align:middle" onclick="this.src='authimg.php?'+Math.random()"></td>
</tr>
</table>
</form>
改進點:使用 $_SESSION 替代隱藏域傳遞驗證碼,防止繞過驗證;mt_rand 替代 rand 提升隨機質量;圖片點擊刷新增強 UX。
<?php
session_start();
header("Content-type: image/png");
// 1. 創建畫布
$im = imagecreate(80, 30); // 寬高適配四位數字
$bg = imagecolorallocate($im, 220, 220, 220); // 淺灰背景
$textColor = imagecolorallocate($im, 0, 0, 0); // 黑色文字
$noiseColor = imagecolorallocate($im, 180, 180, 180); // 干擾色
// 2. 填充背景
imagefill($im, 0, 0, $bg);
// 3. 繪製驗證碼文字
$code = $_SESSION['authnum'];
imagestring($im, 5, 12, 6, $code, $textColor); // 字體 5,座標微調
// 4. 添加干擾像素
for ($i = 0; $i < 80; $i++) {
imagesetpixel($im, mt_rand(0, 79), mt_rand(0, 29), $noiseColor);
}
// 5. 可選:干擾線
for ($i = 0; $i < 5; $i++) {
imageline($im, mt_rand(0, 79), mt_rand(0, 29), mt_rand(0, 79), mt_rand(0, 29), $noiseColor);
}
// 6. 輸出並銷毀
imagepng($im);
imagedestroy($im);
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789')。imagettftext() 繪製抗鋸齒、可旋傾斜字符,大幅提升識別難度。此實現雖屬基礎,但涵蓋驗證碼核心流程,理解其原理有助於評估第三方庫安全性與定制化開發。