萬盛學電腦網

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

PHP 實作中文驗證碼 (CAPTCHA) 完整範例

中文驗證碼比英數字更難被 OCR 識別,提升安全性。本文提供基於 GD 庫的完整實作,含字庫選擇、干擾線、Session 驗證。

完整實作程式碼

<?php
// captcha.php
session_start();

// 1. 字庫:常用中文字 (約 300 字)
$chinese_chars = '的一是不了能好都然沒日於起還發成事只作當想看文無開手十用主行方又如前所本見經頭面公同三已老從動兩長知民樣現分將外但身些與高意進把法此實回二理美點月明其種聲全工己話兒者向情部正名定女問力機給等幾很業最間新什打便位因重被走電四第門相次東政海口使教西再平真聽世氣信北少關並內加化由卻代軍產入先山五太水萬市眼體別處總才場師書比住員九笑性通目華報立馬命張活難神數件安表原車白應路期叫死常提感金何更反合放做系計或司利受光王果親界及今京務制解各任至清物台象記邊共風戰干接它許八特覺望直服毛林題建南度統色字請交愛讓';

// 2. 建立畫布
$width = 130;
$height = 50;
$im = imagecreatetruecolor($width, $height);

// 3. 背景色 (淺灰)
$bg_color = imagecolorallocate($im, 230, 230, 230);
imagefill($im, 0, 0, $bg_color);

// 4. 字體檔案 (需存在:微軟雅黑粗體)
$font_path = __DIR__ . '/fonts/msyhbd.ttc';  // 或 .ttf
if (!file_exists($font_path)) {
    die("字體檔案不存在: $font_path");
}

// 5. 繪製干擾線 (5-10 條)
for ($i = 0; $i < mt_rand(5, 10); $i++) {
    $line_color = imagecolorallocate($im, mt_rand(150, 200), mt_rand(150, 200), mt_rand(150, 200));
    imageline($im, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $line_color);
}

// 6. 繪製干擾點
for ($i = 0; $i < 200; $i++) {
    $dot_color = imagecolorallocate($im, mt_rand(100, 200), mt_rand(100, 200), mt_rand(100, 200));
    imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $dot_color);
}

// 7. 生成 4 個隨機中文字
$captcha_code = '';
$char_count = mb_strlen($chinese_chars, 'UTF-8');
$x = 10;

for ($i = 0; $i < 4; $i++) {
    // 隨機顏色 (深色系)
    $text_color = imagecolorallocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
    
    // 隨機選字
    $char = mb_substr($chinese_chars, mt_rand(0, $char_count - 1), 1, 'UTF-8');
    $captcha_code .= $char;
    
    // 隨機位置、角度、大小
    $x += mt_rand(10, 15) + $i * 5;
    $y = mt_rand(30, 40);
    $angle = mt_rand(-20, 20);
    $size = mt_rand(18, 24);
    
    // 繪文字 (需 FreeType 支援)
    imagettftext($im, $size, $angle, $x, $y, $text_color, $font_path, $char);
}

// 8. 儲存到 Session (供驗證用)
$_SESSION['captcha_code'] = $captcha_code;

// 9. 輸出圖片
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>

前端整合

<!-- HTML 表單 -->
<form action="verify.php" method="post">
    <img src="captcha.php" id="captcha_img" alt="驗證碼" style="cursor:pointer; vertical-align:middle" title="點擊更換">
    <a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='captcha.php?' + Date.now()">看不清?換一張</a>
    <br><br>
    <input type="text" name="captcha" placeholder="請輸入圖片中的 4 個中文字" required>
    <button type="submit">提交</button>
</form>

後端驗證

<?php
// verify.php
session_start();

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

if (empty($input)) {
    die('請輸入驗證碼');
}

// 不分大小寫比對 (中文無大小寫)
if ($input !== $stored) {
    // 失敗:重新生成驗證碼,避免重放攻擊
    unset($_SESSION['captcha_code']);
    die('驗證碼錯誤,請重試');
}

// 成功:清除驗證碼,執行業務邏輯
unset($_SESSION['captcha_code']);
echo "驗證通過!執行業務邏輯...";
// 實際: 登入、註冊、提交表單等
?>

字體檔案取得

  • Windows: C:\Windows\Fonts\msyhbd.ttc (微軟雅黑粗體)
  • Linux: apt-get install fonts-wqy-zenhei → /usr/share/fonts/truetype/wqy/wqy-zenhei.ttc
  • 或下載開源字體:Noto Sans SC, Source Han Sans

進階強化

強化項目實作方式
字體隨機化準備多種字體檔,每次隨機選一種
文字扭曲imagettftext 角度隨機、字符間距隨機、基線浮動
背景噪點隨機像素、隨機弧線、隨機幾何圖形
Session 防重放驗證後立即 unset,單次使用
限制請求頻率同 IP 分鐘最多請求 N 次 captcha.php
無障礙支援提供語音驗證碼選項 (TTS 朗讀)

現代替代方案

  • Google reCAPTCHA v3:無感驗證,行為分析評分
  • hCaptcha:隱私友善、支援中文
  • Turnstile (Cloudflare):免費、無需 Cookie
  • 滑塊/點選驗證:Geetest、NetEase Captcha 等商業 SDK

自建驗證碼適合學習、內部系統、低風險場景;公開網站強烈建議使用成熟第三方服務。

copyright © 萬盛學電腦網 all rights reserved