萬盛學電腦網

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

PHP 圖形驗證碼生成完整教學:從隨機碼到 GD 繪圖、Session 驗證與前端整合

驗證碼核心流程

  1. 生成隨機字元:數字/字母/混合,長度可配置
  2. 建立畫布:GD `imagecreatetruecolor()`
  3. 繪製背景/干擾:顏色、線條、噪點、幾何形狀
  4. 渲染文字:字體、大小、角度、位置隨機化
  5. 存入 Session:供後續驗證比對
  6. 輸出圖片:Header + `imagepng/jpeg/gif` + 銷毀資源

完整生成程式 (captcha.php)

<?php
session_start();

// === 配置區 ===
$config = [
    'length'       => 4,           // 驗證碼長度
    'charset'      => '23456789ABCDEFGHJKLMNPQRSTUVWXYZ', // 排除易混淆字元 0/O, 1/I, 8/B
    'width'        => 120,
    'height'       => 40,
    'font_size'    => 18,
    'font_file'    => __DIR__ . '/fonts/DejaVuSans.ttf', // TTF 字體路徑
    'bg_color'     => [240, 240, 240],
    'text_colors'  => [[0,0,0], [51,51,51], [102,102,102]],
    'line_count'   => 3,
    'dot_count'    => 50,
    'session_key'  => 'captcha_code',
];

// 1. 生成隨機碼
$code = '';
$charset_len = strlen($config['charset']);
for ($i = 0; $i < $config['length']; $i++) {
    $code .= $config['charset'][random_int(0, $charset_len - 1)];
}

// 2. 存入 Session (大小寫不敏感驗證時統一轉大寫)
$_SESSION[$config['session_key']] = strtoupper($code);

// 3. 建立真彩色畫布
$im = imagecreatetruecolor($config['width'], $config['height']);

// 4. 分配顏色
$bg = imagecolorallocate($im, ...$config['bg_color']);
$text_colors = array_map(fn($c) => imagecolorallocate($im, ...$c), $config['text_colors']);
$line_color = imagecolorallocate($im, 180, 180, 180);
$dot_color = imagecolorallocate($im, 150, 150, 150);

// 5. 填充背景
imagefill($im, 0, 0, $bg);

// 6. 繪製干擾線
for ($i = 0; $i < $config['line_count']; $i++) {
    imageline($im,
        random_int(0, $config['width']),
        random_int(0, $config['height']),
        random_int(0, $config['width']),
        random_int(0, $config['height']),
        $line_color
    );
}

// 7. 繪製噪點
for ($i = 0; $i < $config['dot_count']; $i++) {
    imagesetpixel($im,
        random_int(0, $config['width'] - 1),
        random_int(0, $config['height'] - 1),
        $dot_color
    );
}

// 8. 繪製驗證碼文字 (使用 TTF 字體,支援旋轉、抗鋸齒)
$x = 10;
for ($i = 0; $i < $config['length']; $i++) {
    $char = $code[$i];
    $y = random_int($config['font_size'] + 2, $config['height'] - 4);
    $angle = random_int(-15, 15);
    $color = $text_colors[array_rand($text_colors)];
    
    // imagettftext: size, angle, x, y, color, fontfile, text
    imagettftext($im, $config['font_size'], $angle, $x, $y, $color, $config['font_file'], $char);
    
    // 字元寬度估算 + 隨機間距
    $x += $config['font_size'] * 0.7 + random_int(2, 8);
}

// 9. 輸出並清理
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
imagepng($im);
imagedestroy($im);

前端整合 (HTML + JS)

<form method="post" action="verify.php">
    <div class="form-group">
        <label>驗證碼</label>
        <div class="captcha-row">
            <input type="text" name="captcha" id="captcha" maxlength="6" required autocomplete="off">
            <img id="captchaImg" src="captcha.php" alt="驗證碼" title="點擊更換" style="vertical-align:middle;cursor:pointer;margin-left:8px;">
        </div>
    </div>
    <button type="submit">提交</button>
</form>

<script>
document.getElementById('captchaImg').addEventListener('click', function() {
    // 加時間戳防止瀏覽器快取
    this.src = 'captcha.php?' + Date.now();
});

// 表單提交前簡易檢查
document.querySelector('form').addEventListener('submit', function(e) {
    const input = document.getElementById('captcha');
    if (!input.value.trim()) {
        e.preventDefault();
        alert('請輸入驗證碼');
        input.focus();
    }
});

後端驗證 (verify.php)

<?php
session_start();

$input = trim($_POST['captcha'] ?? '');
$expected = $_SESSION['captcha_code'] ?? '';

// 大小寫不敏感比對
if (strtoupper($input) !== $expected) {
    // 失敗:重新導向並帶錯誤訊息
    $_SESSION['error'] = '驗證碼錯誤';
    header('Location: form.php');
    exit;
}

// 成功:銷毀驗證碼 (一次性)
unset($_SESSION['captcha_code']);

// 繼續業務邏輯...
echo '驗證通過!';

進階強化方案

1. 算術/邏輯驗證碼 (無障礙友善)

<?php
// 生成簡單算式:3 + 5 = ?
$a = random_int(1, 9);
$b = random_int(1, 9);
$op = random_int(0, 1) ? '+' : '-';
$question = "$a $op $b = ?";
$answer = $op === '+' ? $a + $b : $a - $b;

$_SESSION['captcha_answer'] = (string)$answer;
// 圖片繪製 $question 文字...

2. 滑塊/點選/圖標驗證 (前端互動)

  • 前端 Canvas/JS 實作滑塊拼圖、點選倒序文字、選擇特定圖標
  • 後端驗證軌跡/座標/順序
  • 推薦成熟方案:Geetest 極驗、Google reCAPTCHA v3、hCaptcha、Turnstile (Cloudflare)

3. 無障礙支援

  • 提供 語音驗證碼:TTS 生成音檔 (Web Speech API 或後端合成)
  • `驗證碼,點擊更換` + `aria-label`
  • 確保色彩對比度符合 WCAG AA

4. 安全強化

威脅對策
暴力嘗試IP/Session 限流 (每分鐘 5 次)、失敗鎖定 15 分鐘
Session 固定驗證後 `session_regenerate_id(true)`
自動識別 (OCR/AI)增加干擾、扭曲、隨機字體、語音/滑塊替代
重放攻擊驗證碼一次性、時間戳過期 (5-10 分鐘)
繞過前端直接呼叫 APIAPI 端同樣驗證 Session、CSRF Token 雙重保護

現代替代方案對比

方案優點缺點適用場景
自建 GD 驗證碼完全控制、無外部依賴、免費維護成本、易被 AI 破解、無障礙弱簡單專案、內網、學習用途
Google reCAPTCHA v3零互動、風險評分、Google 信譽隱私疑慮、中國大陸不可用、需後端驗證公開網站、表單保護
hCaptcha / Turnstile隱私友善、全球可用、有收益分成需註冊、免費版有限制替代 reCAPTCHA
Geetest 極驗行為驗證、滑塊/點選、中文支援好商業收費、需 SDK 整合中文市場、高安全需求
Cloudflare Turnstile免費、無隱私追蹤、易整合依賴 Cloudflare 生態現代網站首選

常見問題排查

圖片顯示破圖/空白
1. 檢查 GD 擴充套件 `php -m | grep gd` 2. 確認 `imagecreatetruecolor` 存在 3. 輸出前無任何 `echo`/`var_dump`/空白/BOM 4. TTF 字體路徑正確、可讀
Session 驗證總是失敗
1. 所有檔案開頭 `session_start()` 2. Cookie 域名/路徑/安全性設定一致 3. 瀏覽器接受 Cookie 4. `session.save_path` 可寫
中文亂碼/方塊字
TTF 字體需支援中文字符,推薦 Noto Sans CJK、思源黑體、微軟雅黑
效能問題
啟用 OPcache、考慮快取生成的圖片 (Key: code+config hash)、或改用外部服務

總結

自建 GD 驗證碼適合學習與簡單場景,生產環境強烈建議接入成熟的行為驗證服務 (Turnstile/hCaptcha/reCAPTCHA),兼顧安全性、無障礙、維護成本與用戶體驗。若必須自建,請務必實作:一次性驗證、速率限制、HTTPS 傳輸、無障礙替代方案。

copyright © 萬盛學電腦網 all rights reserved