核心原理
- Session 儲存驗證碼字串 (伺服端)。
- GD 繪製畫布 → 填充背景 → 繪製干擾線/點 → 繪製扭曲字符 → 輸出 PNG。
- 前端
<img src="captcha.php"> 請求圖片,用戶輸入提交表單。
- 後端比對
$_POST['captcha'] 與 $_SESSION['captcha'] (不區分大小寫)。
完整驗證碼類別
<?php
class Captcha {
private int $width = 130;
private int $height = 50;
private int $length = 4;
private string $charset = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; // 排除易混淆字符
private string $fontPath;
private int $fontSize = 24;
private string $sessionKey = 'captcha_code';
public function __construct(array $options = []) {
foreach ($options as $k => $v) if (property_exists($this, $k)) $this->$k = $v;
if (!$this->fontPath) $this->fontPath = __DIR__ . '/fonts/msyh.ttc'; // 需自備 TTF
if (!file_exists($this->fontPath)) throw new Exception("字體檔案不存在: {$this->fontPath}");
if (session_status() === PHP_SESSION_NONE) session_start();
}
/** 生成隨機碼並存入 Session */
public function generate(): string {
$code = '';
$max = strlen($this->charset) - 1;
for ($i = 0; $i < $this->length; $i++) {
$code .= $this->charset[random_int(0, $max)];
}
$_SESSION[$this->sessionKey] = $code;
return $code;
}
/** 輸出驗證碼圖片 (直接輸出到瀏覽器) */
public function output(): void {
$code = $this->generate();
$img = imagecreatetruecolor($this->width, $this->height);
// 背景色 (淺灰)
$bg = imagecolorallocate($img, 240, 240, 240);
imagefill($img, 0, 0, $bg);
// 干擾線 (5-8 條)
for ($i = 0; $i < random_int(5, 8); $i++) {
$color = imagecolorallocate($img, random_int(150,200), random_int(150,200), random_int(150,200));
imageline($img, random_int(0,$this->width), random_int(0,$this->height),
random_int(0,$this->width), random_int(0,$this->height), $color);
}
// 干擾點 (50-100 個)
for ($i = 0; $i < random_int(50, 100); $i++) {
$color = imagecolorallocate($img, random_int(100,200), random_int(100,200), random_int(100,200));
imagesetpixel($img, random_int(0,$this->width), random_int(0,$this->height), $color);
}
// 繪製字符 (逐字符隨機旋轉、位移、顏色)
$charW = $this->width / $this->length;
for ($i = 0; $i < $this->length; $i++) {
$char = $code[$i];
$angle = random_int(-25, 25);
$x = $i * $charW + random_int(5, 15);
$y = random_int($this->height * 0.4, $this->height * 0.7);
$color = imagecolorallocate($img, random_int(0,80), random_int(0,80), random_int(0,80));
imagettftext($img, $this->fontSize, $angle, $x, $y, $color, $this->fontPath, $char);
}
// 輸出
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
imagepng($img);
imagedestroy($img);
}
/** 驗證用戶輸入 (不區分大小寫,驗證後銷毀) */
public function verify(string $input): bool {
$code = $_SESSION[$this->sessionKey] ?? '';
unset($_SESSION[$this->sessionKey]); // 一次性,防暴力重試
return strtoupper($input) === strtoupper($code);
}
}
前端整合 (HTML + AJAX 驗證)
<form id="loginForm" method="post" action="login.php">
<input type="text" name="username" placeholder="用戶名" required><br>
<input type="password" name="password" placeholder="密碼" required><br>
<div class="captcha-row">
<input type="text" name="captcha" id="captchaInput" placeholder="驗證碼" required style="width:80px">
<img id="captchaImg" src="captcha.php" alt="驗證碼" style="vertical-align:middle; cursor:pointer" title="點擊換一張">
<a href="javascript:void(0)" onclick="refreshCaptcha()">看不清
</div>
<button type="submit">登入</button>
</form>
<script>
function refreshCaptcha() {
document.getElementById('captchaImg').src = 'captcha.php?' + Date.now();
}
document.getElementById('captchaImg').addEventListener('click', refreshCaptcha);
// 可選:AJAX 預驗證
document.getElementById('captchaInput').addEventListener('blur', function() {
const val = this.value.trim();
if (val.length >= 4) {
fetch('verify_captcha.php', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'},
body: 'captcha=' + encodeURIComponent(val)
}).then(r => r.json()).then(data => {
if (!data.valid) this.setCustomValidity('驗證碼錯誤');
else this.setCustomValidity('');
});
}
});
</script>
後端驗證端點
captcha.php (生成圖片)
<?php
require 'Captcha.php';
$captcha = new Captcha([
'width' => 130, 'height' => 50, 'length' => 4,
'fontPath' => __DIR__ . '/fonts/msyh.ttc',
]);
$captcha->output();
verify_captcha.php (AJAX 驗證)
<?php
require 'Captcha.php';
session_start();
$captcha = new Captcha();
$input = $_POST['captcha'] ?? '';
echo json_encode(['valid' => $captcha->verify($input)]);
login.php (表單提交驗證)
<?php
session_start();
require 'Captcha.php';
$captcha = new Captcha();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!$captcha->verify($_POST['captcha'] ?? '')) {
die('驗證碼錯誤');
}
// 正常登入邏輯...
echo '登入成功';
}
進階強化 (無障礙/安全/效能)
- 語音驗證碼:提供音頻播放按鈕,後端用 TTS 生成 MP3 (Google TTS / 百度語音 / 本地 eSpeak)。
- 行為驗證:整合 Google reCAPTCHA v3 / hCaptcha / Geetest,完全替代圖形驗證碼。
- 字體隨機化:準備 5-10 款 TTF 字體,每次隨機選一款,增加機器識別難度。
- Session 防囤積:定期清理舊 Session 檔案,或用 Redis 存儲驗證碼並設 TTL。
- 限流:同 IP 分鐘請求驗證碼圖片次數限制 (Nginx limit_req / PHP 計數器)。