萬盛學電腦網

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

PHP 打造高顏值圖形驗證碼:抗干擾、支援 TTF 字體、可調整難度

功能特色

  • 使用 TrueType 字體 (TTF) 渲染,字形清晰美觀
  • 隨機旋轉、位移、顏色,有效對抗 OCR 識別
  • 干擾元素:星狀點、隨機曲線、噪點
  • 支援大小寫不敏感驗證,提升用戶體驗
  • 字體檔案隨專案部署,免依賴系統字體

完整實作程式碼

<?php
/**
 * 圖形驗證碼產生器
 * 需求:PHP GD 擴展、FreeType 支援、TTF 字體檔
 */
class Captcha {
    private $width   = 120;
    private $height  = 40;
    private $length  = 4;
    private $fontSize = 22;
    private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; // 排除易混淆字元
    private $fontFile = __DIR__ . '/fonts/segoesc.ttf'; // 專案內字體
    private $sessionKey = 'captcha_code';

    public function __construct(array $options = []) {
        foreach ($options as $k => $v) {
            if (property_exists($this, $k)) $this->$k = $v;
        }
    }

    public function generate() {
        // 建立真彩色畫布
        $im = imagecreatetruecolor($this->width, $this->height);
        $bg = imagecolorallocate($im, 255, 255, 255);
        imagefill($im, 0, 0, $bg);

        // 產生隨機字串
        $code = '';
        $maxIdx = strlen($this->charset) - 1;
        for ($i = 0; $i < $this->length; $i++) {
            $code .= $this->charset[random_int(0, $maxIdx)];
        }

        // 儲存至 Session (小寫比對)
        session_start();
        $_SESSION[$this->sessionKey] = strtolower($code);

        // 1. 繪製干擾星星
        for ($i = 0; $i < $this->width; $i++) {
            $color = imagecolorallocate($im,
                random_int(200, 255), random_int(200, 255), random_int(200, 255));
            imagestring($im, random_int(1, 5),
                random_int(0, $this->width), random_int(0, $this->height),
                '*', $color);
        }

        // 2. 繪製干擾線 (數量 = 字元數)
        for ($i = 0; $i < $this->length; $i++) {
            $color = imagecolorallocate($im,
                random_int(0, 255), random_int(0, 255), random_int(0, 255));
            imageline($im, 0, random_int(0, $this->height),
                $this->width, random_int(0, $this->height), $color);
        }

        // 3. 繪製驗證碼字元
        $xStep = intval($this->width / $this->length);
        $yPos  = intval($this->height * 0.65);

        for ($i = 0; $i < $this->length; $i++) {
            $color = imagecolorallocate($im,
                random_int(0, 120), random_int(0, 120), random_int(0, 120));
            $angle = random_int(-25, 25);
            $x = $i * $xStep + random_int(3, 8);
            imagettftext($im, $this->fontSize, $angle, $x, $yPos, $color, $this->fontFile, $code[$i]);
        }

        // 輸出 PNG
        header('Content-Type: image/png');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');
        imagepng($im);
        imagedestroy($im);
    }

    /** 驗證用戶輸入 */
    public static function verify(string $input, string $sessionKey = 'captcha_code'): bool {
        session_start();
        if (empty($_SESSION[$sessionKey])) return false;
        $valid = strcasecmp($_SESSION[$sessionKey], $input) === 0;
        unset($_SESSION[$sessionKey]); // 一次性驗證
        return $valid;
    }
}

// 直接輸出驗證碼圖片
if (php_sapi_name() !== 'cli') {
    (new Captcha())->generate();
}

部署注意事項

  1. 字體檔案:將 segoesc.ttf (或任意 TTF) 放置於 fonts/ 目錄,確保 Web 伺服器可讀取。
  2. GD 擴展:需編譯支援 FreeType (`--with-freetype-dir`),驗證方式:php -m | grep gd 並確認 gd_info()['FreeType Support'] 為 true。
  3. Session 啟動:專案若已有統一 Session 初始化,請移除類別內的 session_start(),避免重複啟動警告。

前端整合範例

<!-- HTML -->
<img id="captchaImg" src="/captcha.php" alt="驗證碼" style="vertical-align:middle;cursor:pointer" title="點擊更換">
<input type="text" name="captcha" maxlength="4" placeholder="輸入驗證碼">

<script>
document.getElementById('captchaImg').onclick = function() {
    this.src = '/captcha.php?' + Date.now(); // 防快取
};
</script>

驗證端點範例

<?php
require_once 'Captcha.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = $_POST['captcha'] ?? '';
    if (Captcha::verify($input)) {
        echo json_encode(['success' => true, 'msg' => '驗證通過']);
    } else {
        echo json_encode(['success' => false, 'msg' => '驗證碼錯誤']);
    }
}

進階擴充方向

  • 點選/滑塊驗證:前端 Canvas 繪製,後端驗證座標容差
  • 算術/邏輯題:`3 + 5 = ?`、`星期三的英文縮寫?`,提升機器識別難度
  • 語音驗證碼:無障礙支援,使用 espeak 或 TTS API 產生音檔
  • 分散式 Session:Redis 儲存驗證碼,支援多節點部署

此驗證碼類別輕量、無依賴、易於客製化,適合中小型專案快速整合。高安全性場景建議改用 Google reCAPTCHA v3 或 hCaptcha 等行業標準方案。

copyright © 萬盛學電腦網 all rights reserved