<?php
/**
* 圖形驗證碼產生器
* 需求:PHP GD 擴展、FreeType 支援、TTF 字體檔
*/
class Captcha {
private $width = 120;
private $height = 40;
private $length = 4;
private $fontSize = 22;
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; // 排除易混淆字元
private $fontFile = __DIR__ . '/fonts/segoesc.ttf'; // 專案內字體
private $sessionKey = 'captcha_code';
public function __construct(array $options = []) {
foreach ($options as $k => $v) {
if (property_exists($this, $k)) $this->$k = $v;
}
}
public function generate() {
// 建立真彩色畫布
$im = imagecreatetruecolor($this->width, $this->height);
$bg = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bg);
// 產生隨機字串
$code = '';
$maxIdx = strlen($this->charset) - 1;
for ($i = 0; $i < $this->length; $i++) {
$code .= $this->charset[random_int(0, $maxIdx)];
}
// 儲存至 Session (小寫比對)
session_start();
$_SESSION[$this->sessionKey] = strtolower($code);
// 1. 繪製干擾星星
for ($i = 0; $i < $this->width; $i++) {
$color = imagecolorallocate($im,
random_int(200, 255), random_int(200, 255), random_int(200, 255));
imagestring($im, random_int(1, 5),
random_int(0, $this->width), random_int(0, $this->height),
'*', $color);
}
// 2. 繪製干擾線 (數量 = 字元數)
for ($i = 0; $i < $this->length; $i++) {
$color = imagecolorallocate($im,
random_int(0, 255), random_int(0, 255), random_int(0, 255));
imageline($im, 0, random_int(0, $this->height),
$this->width, random_int(0, $this->height), $color);
}
// 3. 繪製驗證碼字元
$xStep = intval($this->width / $this->length);
$yPos = intval($this->height * 0.65);
for ($i = 0; $i < $this->length; $i++) {
$color = imagecolorallocate($im,
random_int(0, 120), random_int(0, 120), random_int(0, 120));
$angle = random_int(-25, 25);
$x = $i * $xStep + random_int(3, 8);
imagettftext($im, $this->fontSize, $angle, $x, $yPos, $color, $this->fontFile, $code[$i]);
}
// 輸出 PNG
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
imagepng($im);
imagedestroy($im);
}
/** 驗證用戶輸入 */
public static function verify(string $input, string $sessionKey = 'captcha_code'): bool {
session_start();
if (empty($_SESSION[$sessionKey])) return false;
$valid = strcasecmp($_SESSION[$sessionKey], $input) === 0;
unset($_SESSION[$sessionKey]); // 一次性驗證
return $valid;
}
}
// 直接輸出驗證碼圖片
if (php_sapi_name() !== 'cli') {
(new Captcha())->generate();
}
segoesc.ttf (或任意 TTF) 放置於 fonts/ 目錄,確保 Web 伺服器可讀取。php -m | grep gd 並確認 gd_info()['FreeType Support'] 為 true。session_start(),避免重複啟動警告。<!-- HTML -->
<img id="captchaImg" src="/captcha.php" alt="驗證碼" style="vertical-align:middle;cursor:pointer" title="點擊更換">
<input type="text" name="captcha" maxlength="4" placeholder="輸入驗證碼">
<script>
document.getElementById('captchaImg').onclick = function() {
this.src = '/captcha.php?' + Date.now(); // 防快取
};
</script>
<?php
require_once 'Captcha.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = $_POST['captcha'] ?? '';
if (Captcha::verify($input)) {
echo json_encode(['success' => true, 'msg' => '驗證通過']);
} else {
echo json_encode(['success' => false, 'msg' => '驗證碼錯誤']);
}
}
espeak 或 TTS API 產生音檔此驗證碼類別輕量、無依賴、易於客製化,適合中小型專案快速整合。高安全性場景建議改用 Google reCAPTCHA v3 或 hCaptcha 等行業標準方案。