功能特點
- 4 位大寫字母隨機驗證碼
- 干擾線、隨機字體大小/顏色/位置
- Session 儲存驗證碼 (小寫),5 秒內重複請求不更新
- 支援 PNG/JPEG 輸出,無 GD 時回退靜態圖片
- 完整 HTTP 快取控制標頭
完整程式碼 (captcha.php)
<?php
/**
* 類 QQ 風格驗證碼
* 使用:
表單欄位名建議 captcha_code
*/
session_start();
// Session 儲存路徑 (視專案調整)
$sessPath = __DIR__ . '/../data/sessions';
if (is_writeable($sessPath) && is_readable($sessPath)) {
session_save_path($sessPath);
}
// 產生 4 位大寫字母
$rnd = '';
for ($i = 0; $i < 4; $i++) $rnd .= chr(mt_rand(65, 90)); // A-Z
// 5 秒內不重新產生 (防刷新圖片閃爍)
$now = time();
if (empty($_SESSION['captcha_code']) || empty($_SESSION['captcha_time']) || ($now - $_SESSION['captcha_time'] > 5)) {
$_SESSION['captcha_code'] = strtolower($rnd); // 儲存小寫,驗證時不區分大小寫
$_SESSION['captcha_time'] = $now;
}
$code = $_SESSION['captcha_code'];
$len = strlen($code);
if (function_exists('imagecreatetruecolor')) {
// 使用 TrueColor 畫布品質更好
$img = imagecreatetruecolor(80, 30);
// 背景色 (淡藍灰)
$bg = imagecolorallocate($img, 240, 243, 248);
imagefill($img, 0, 0, $bg);
// 干擾線 (2 條)
for ($j = 1; $j <= 2; $j++) {
$lineColor = imagecolorallocate($img, mt_rand(174, 218), mt_rand(190, 225), mt_rand(217, 237));
imageline($img, 0, $j + mt_rand(1, 10), 80, $j + mt_rand(1, 10), $lineColor);
}
// 繪製字元
for ($i = 0; $i < $len; $i++) {
$fontColor = imagecolorallocate($img, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
$size = mt_rand(3, 5); // GD 內建字體 1-5
$x = $i * 18 + mt_rand(2, 6);
$y = mt_rand(2, 10);
imagechar($img, $size, $x, $y, strtoupper($code[$i]), $fontColor);
}
// 輸出標頭
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Expires: 0');
// 優先 PNG
if (function_exists('imagepng')) {
header('Content-Type: image/png');
imagepng($img);
} else {
header('Content-Type: image/jpeg');
imagejpeg($img, null, 85);
}
imagedestroy($img);
exit;
}
// 無 GD 環境回退
$_SESSION['captcha_code'] = 'abcd';
$_SESSION['captcha_time'] = '';
header('Content-Type: image/png');
header('Pragma: no-cache');
header('Cache-Control: no-cache');
header('Expires: 0');
readfile(__DIR__ . '/data/vdcode.png'); // 預備一張靜態圖片
exit;
?>
前端整合範例
<form action="verify.php" method="post">
<img src="captcha.php" id="captchaImg" style="vertical-align:middle; cursor:pointer" title="點擊更換">
<a href="javascript:" onclick="document.getElementById('captchaImg').src='captcha.php?'+Date.now()">看不清?換一張</a><br>
<input type="text" name="captcha_code" maxlength="4" required placeholder="輸入驗證碼">
<button type="submit">提交</button>
</form>
後端驗證 (verify.php)
<?php
session_start();
$input = strtolower(trim($_POST['captcha_code'] ?? ''));
$stored = $_SESSION['captcha_code'] ?? '';
if ($input === '' || $stored === '' || $input !== $stored) {
die('驗證碼錯誤或已過期');
}
// 驗證通過,銷毀防止重用
unset($_SESSION['captcha_code'], $_SESSION['captcha_time']);
// 後續業務邏輯...
echo '驗證通過,處理表單...';
?>
安全與體驗增強建議
- 字元集擴充:加入數字 0-9、排除易混淆字元 (O/0, I/1, Z/2)。
- TTF 字體:用
imagettftext() 載入 .ttf 字體,效果更佳、可旋傾斜。
- 干擾點/曲線:
imagesetpixel()、imagebezier() (需 GD 2.0+)。
- 驗證碼聯盟/第三方:高安全性場景建議接入 Google reCAPTCHA v3、Geetest、騰訊防水牆等行為驗證。
- Session 安全:
session.cookie_httponly=1, session.cookie_secure=1 (HTTPS)、session.use_strict_mode=1。