驗證碼(CAPTCHA)是「全自動區分計算機和人類的圖靈測試」縮寫。通過生成包含隨機字符的圖片,並添加干擾像素防止 OCR 識別,要求用戶肉眼識別並輸入,從而阻擋機器人自動註冊、登錄、灌水等惡意行為。
經典實現將邏輯分為兩個文件:
<?php
// 初始化隨機種子(PHP 4.2+ 可省略)
srand((double)microtime() * 1000000);
// 驗證用戶提交
if (isset($_POST['authinput'])) {
if (strcmp($_POST['authnum'], $_POST['authinput']) == 0) {
echo "驗證成功!";
} else {
echo "驗證失敗!";
}
}
// 生成 4 位數字驗證碼(1000-9999)
while (($authnum = rand() % 10000) < 1000);
?>
<form action="authpage.php" method="post">
<table>
<tr><td>請輸入驗證碼:<input type="text" name="authinput" style="width:80px"></td></tr>
<tr><td>
<input type="submit" name="驗證" value="提交驗證碼">
<input type="hidden" name="authnum" value="<?php echo $authnum; ?>">
<img src="authimg.php?authnum=<?php echo $authnum; ?>" alt="驗證碼">
</td></tr>
</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, 0, 0, $gray); // 填充背景
// 繪製驗證碼文字
imagestring($im, 5, 10, 8, $_GET['authnum'], $black);
// 添加 50 個干擾像素
for ($i = 0; $i < 50; $i++) {
imagesetpixel($im, rand() % 70, rand() % 30, $black);
}
ImagePNG($im);
ImageDestroy($im);
?>
上述簡單實現存在明文傳輸驗證碼、無 Session 綁定等問題。商業應用建議採用以下流程:
session_start()。authimg.php 中生成驗證碼,計算 MD5 後存入 $_SESSION['captcha_md5']。<?php
session_start();
header("Content-type: image/PNG");
// ... 生成圖片及 $code ...
$_SESSION['captcha_md5'] = md5(strtoupper($code)); // 不區分大小寫
// ... 輸出圖片 ...
?>
<?php
session_start();
if (isset($_POST['captcha_input'])) {
$input_md5 = md5(strtoupper($_POST['captcha_input']));
if ($input_md5 === $_SESSION['captcha_md5']) {
echo "驗證通過";
unset($_SESSION['captcha_md5']); // 一次性使用
} else {
echo "驗證失敗";
}
}
?>
imagettftext) 實現字符扭曲、旋轉,大幅提高 OCR 識別難度。gregwar/captcha、mewebstudio/captcha)或第三方服務(reCAPTCHA、hCaptcha)。Cache-Control: no-store 防止緩存重用。驗證碼是 Web 安全基礎防線之一。從簡單的數字圖片到行為分析型驗證,技術不斷演進。開發者應根據業務風險等級選擇合適方案,並持續關注對抗技術演進。