完整驗證碼生成器 (captcha.php)
<?php
session_start();
// 1. 環境檢查:確認 GD 關鍵函數存在
$requiredFuncs = ['imagecreatetruecolor', 'imagecolorallocate', 'imagefill', 'imagestring',
'imageline', 'imagerotate', 'imagedestroy', 'imagecolorallocatealpha',
'imageellipse', 'imagepng'];
$gdEnabled = true;
foreach ($requiredFuncs as $func) {
if (!function_exists($func)) { $gdEnabled = false; break; }
}
ob_clean(); // 清除前序輸出
if ($gdEnabled) {
// 2. 字元池:排除易混淆字元 (o/O/0, i/I/1/l, etc.)
$consonants = 'bcdfghjkmnpqrstvwxyz23456';
$vowels = 'aeiou23456789';
// 3. 產生 4 碼驗證碼 (子音-母音交替,易讀)
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $consonants[mt_rand(0, strlen($consonants)-1)];
$code .= $vowels[mt_rand(0, strlen($vowels)-1)];
}
$code = substr($code, 0, 4); // 取前 4 碼
$_SESSION['checkcode'] = strtolower($code); // 存入 Session (不區分大小寫)
// 4. 畫布設定
$imgW = strlen($code) * 20 + 20; // 動態寬度
$imgH = 40;
$im = imagecreatetruecolor($imgW, $imgH);
// 5. 顏色池
$bg = imagecolorallocate($im, mt_rand(220, 255), mt_rand(220, 255), mt_rand(220, 255));
$textColors = [
imagecolorallocate($im, mt_rand(0, 50), mt_rand(0, 50), mt_rand(0, 50)),
imagecolorallocate($im, mt_rand(0, 50), mt_rand(0, 50), mt_rand(200, 255)),
imagecolorallocate($im, mt_rand(200, 255), mt_rand(0, 50), mt_rand(0, 50)),
imagecolorallocate($im, mt_rand(200, 255), mt_rand(0, 50), mt_rand(200, 255)),
];
$noiseColor = imagecolorallocatealpha($im, mt_rand(100, 180), mt_rand(100, 180), mt_rand(100, 180), 60);
$borderColor = imagecolorallocate($im, 150, 150, 180);
// 6. 填背景
imagefill($im, 0, 0, imagecolorallocate($im, 250, 252, 255));
// 7. 繪製字元:隨機字體、旋轉、位置
$fonts = [
PHPCMS_ROOT . 'include/fonts/ALGER.TTF',
PHPCMS_ROOT . 'include/fonts/ARIALNI.TTF',
PHPCMS_ROOT . 'include/fonts/arial.ttf',
];
for ($i = 0; $i < 4; $i++) {
$x = 10 + $i * 22 + mt_rand(-2, 2);
$y = 28 + mt_rand(-3, 3);
$angle = mt_rand(-25, 25);
$font = $fonts[array_rand($fonts)];
$color = $textColors[array_rand($textColors)];
imagettftext($im, 20, $angle, $x, $y, $color, $font, $code[$i]);
}
// 8. 干擾元素:噪點、干擾線、橢圓
for ($i = 0; $i < 80; $i++) {
imagesetpixel($im, mt_rand(0, $imgW), mt_rand(0, $imgH), $noiseColor);
}
for ($i = 0; $i < 6; $i++) {
imageline($im, mt_rand(0, $imgW), mt_rand(0, $imgH), mt_rand(0, $imgW), mt_rand(0, $imgH), $noiseColor);
imageellipse($im, mt_rand(0, $imgW), mt_rand(0, $imgH), mt_rand(5, 30), mt_rand(5, 30), $noiseColor);
}
// 9. 邊框
imagerectangle($im, 0, 0, $imgW-1, $imgH-1, $borderColor);
// 10. 輸出
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
} else {
// 11. 降級方案:靜態圖片池
$files = glob(PHPCMS_ROOT . 'images/checkcode/*.jpg');
if (empty($files)) exit('驗證碼圖片資源遺失');
$pick = $files[array_rand($files)];
$_SESSION['checkcode'] = strtolower(substr(basename($pick), 0, 4));
header('Content-Type: image/jpeg');
readfile($pick);
}
?>
前端整合範例
<img src="captcha.php?t== time() ?>" id="captcha" onclick="this.src='captcha.php?t='+Date.now()" style="cursor:pointer" title="點擊更換" />
<input type="text" name="captcha_input" maxlength="4" required />
後端驗證
<?php
session_start();
if (empty($_POST['captcha_input']) || strtolower($_POST['captcha_input']) !== ($_SESSION['checkcode'] ?? '')) {
exit('驗證碼錯誤');
}
// 驗證通過後建議清除,防止重放
unset($_SESSION['checkcode']);
?>
安全性與無障礙強化建議
- 音頻驗證碼: 為視障用戶提供語音播放選項 (TTS 或預錄音檔)。
- 速率限制: 同 IP 每分鐘請求上限、失敗鎖定。
- 避免 Session 固定攻擊: 登入前
session_regenerate_id(true)。
- 考慮現代替代方案: hCaptcha / reCAPTCHA v3 (行為分析)、Turnstile (Cloudflare) — 無感驗證、維運成本低。