首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 英文單字驗證碼生成:詞庫隨機抽樣與圖片合成實作

     編輯:PHP 相關知識

單字驗證碼優勢與適用場景

傳統亂碼驗證碼使用者體驗差,單字驗證碼優勢明顯:

  • 易讀性高:真實英文單字,人類辨譽率近 100%
  • 記憶友善:可語音唸出、支援無障礙存取
  • 反 OCR 強:字典詞彙變化大,機器學習模型難以通用
  • 國際化:無語系障礙,適合多語系網站

核心實作邏輯

1. 詞庫檔案結構

words.txt:每行一個單字,建議 5,000+ 詞彙,長度 4-8 字元

apple
banana
computer
developer
elephant
...

2. 高效隨機抽樣演算法

function vcaptcha_read_code($wordlist_file) {
    $fp = @fopen($wordlist_file, 'rb');
    if (!$fp) return false;
    
    $fsize = filesize($wordlist_file);
    if ($fsize < 32) return false;
    
    // 讀取隨機 128 位元組區塊 (避免載入整個大檔)
    $max = min(128, $fsize);
    fseek($fp, mt_rand(0, $fsize - $max), SEEK_SET);
    $data = fread($fp, 128);
    fclose($fp);
    
    // 正規化換行符
    $data = preg_replace("/\r?\n/", "\n", $data);
    
    // 隨機起始位置 (前 100 字元內找換行)
    $start = strpos($data, "\n", mt_rand(0, min(100, strlen($data)-1))) + 1;
    // 找結束換行
    $end = strpos($data, "\n", $start);
    
    return strtolower(substr($data, $start, $end - $start));
}

**關鍵優化**:不載入整個詞庫至記憶體,適合大型詞庫檔案。

3. 圖片合成與文字繪製

$width = 145; $height = 45;
$authcode = vcaptcha_read_code('words.txt');
$letters = strlen($authcode);

$bg = 'bg/captcha_bg3.jpg';
$img_bg = imagecreatefromjpeg($bg);
$bg_width = imagesx($img_bg); $bg_height = imagesy($img_bg);

$img_org = imagecreatetruecolor($width, $height);
// 縮放背景至目標尺寸
imagecopyresampled($img_org, $img_bg, 0, 0, 0, 0, $width, $height, $bg_width, $bg_height);
imagedestroy($img_bg);

$white = imagecolorallocate($img_org, 255, 255, 255);
imagerectangle($img_org, 0, 0, $width-1, $height-1, $white);  // 邊框

// 置中繪製文字
$x = ($width - imagefontwidth(5) * $letters) / 2;
$y = ($height - imagefontheight(5)) / 2;
imagestring($img_org, 5, $x, $y, $authcode, $white);

// 輸出
header('Content-Type: image/png');
imagepng($img_org);
imagedestroy($img_org);

前端整合與換碼機制

<img id="captcha_img" title="點擊更換驗證碼" 
     src="captcha_word.php" onclick="refreshCaptcha()" />

<script>
function refreshCaptcha() {
    const img = document.getElementById('captcha_img');
    img.src = 'captcha_word.php?' + Math.random();  // 破解快取
}
</script>

進階強化方向

  1. 字體升級:使用 imagettftext() + TTF 字體,支援反鋸齒、旋傾、字間距
  2. 干擾層:疊加半透明幾何圖形、貝塞爾曲線、隨機字元殘片
  3. 動態詞庫:依使用者語系載入對應詞庫 (英文/日文/德文等)
  4. 難度自適應:失敗次數增加 → 單字長度增加/干擾強度提升
  5. 語音輔助:整合 TTS API 提供單字發音,符合 WCAG 2.1 AA

詞庫來源建議

  • SCOWL (Spell Checker Oriented Word Lists) - 開源英文詞庫
  • WordNet - 普林斯頓大學語義詞庫
  • 常用 3000-5000 單字 (TOEFL/GRE/雅思核心詞)
  • 專案業務術語詞庫 (電商/金融/醫療專業詞彙)

單字驗證碼在安全性與使用體驗間取得良好平衡,配合詞庫豐富度與圖片干擾強度,可有效抵禦自動化攻擊並保持使用者友善度。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved