萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 驗證碼(CAPTCHA)技術原理與實現完整指南

什麼是驗證碼?

驗證碼(CAPTCHA)是「全自動區分計算機和人類的圖靈測試」縮寫。通過生成包含隨機字符的圖片,並添加干擾像素防止 OCR 識別,要求用戶肉眼識別並輸入,從而阻擋機器人自動註冊、登錄、灌水等惡意行為。

基礎實現:兩文件分離架構

經典實現將邏輯分為兩個文件:

  • authpage.php:主頁面,生成隨機碼、顯示表單、驗證用戶輸入。
  • authimg.php:圖片生成器,根據傳入參數繪製驗證碼圖片。

1. authpage.php - 主邏輯與表單

<?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>

2. authimg.php - 圖片生成

<?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 綁定等問題。商業應用建議採用以下流程:

  1. 啟用 Session:session_start()。
  2. 服務端生成並存儲:在 authimg.php 中生成驗證碼,計算 MD5 後存入 $_SESSION['captcha_md5']。
  3. 驗證時比對哈希:用戶提交時,對輸入計算 MD5,與 Session 中值比對,防止明文暴露與重放攻擊。

增強版 authimg.php 片段

<?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 "驗證失敗";
    }
}
?>

優化建議

  • 使用 TTF 字體 (imagettftext) 實現字符扭曲、旋轉,大幅提高 OCR 識別難度。
  • 增加干擾線、曲線、噪點、背景圖片。
  • 考慮使用成熟庫(如 gregwar/captcha、mewebstudio/captcha)或第三方服務(reCAPTCHA、hCaptcha)。
  • 驗證碼圖片應設置 Cache-Control: no-store 防止緩存重用。

結語

驗證碼是 Web 安全基礎防線之一。從簡單的數字圖片到行為分析型驗證,技術不斷演進。開發者應根據業務風險等級選擇合適方案,並持續關注對抗技術演進。

copyright © 萬盛學電腦網 all rights reserved