生成包含中文漢字、數字、干擾線、噪點的 PNG 驗證碼圖片,儲存至 Session 驗證。
<?php
session_start();
// 1. 字元庫:中文語句 + 十六進位字元
$text = '芸芸眾生綠水青山名勝古跡敞開心胸便會雲蒸霞蔚快樂將永遠伴隨著你';
$text = iconv('GBK', 'UTF-8', $text); // 若原檔為 GBK 編碼
if (!mb_check_encoding($text, 'UTF-8')) exit('編碼錯誤');
$chars = [];
for ($i = 0, $len = mb_strlen($text, 'UTF-8'); $i < $len; $i++) {
$chars[] = mb_substr($text, $i, 1, 'UTF-8');
}
// 2. 產生 4 字驗證碼 (中文/十六進位隨機混合)
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= (mt_rand(0, 1) === 0) ? $chars[mt_rand(0, count($chars)-1)] : dechex(mt_rand(0, 15));
}
$_SESSION['captcha'] = $code;
// 3. 建立真彩色圖片
$width = 130; $height = 40;
$img = imagecreatetruecolor($width, $height);
// 4. 分配顏色
$bg = imagecolorallocate($img, 240, 240, 240); // 淺灰背景
$txt = imagecolorallocate($img, 30, 30, 30); // 深灰文字
$noise = imagecolorallocate($img, 180, 180, 180);
$line = imagecolorallocate($img, 100, 100, 100);
imagefill($img, 0, 0, $bg);
// 5. 繪製文字 (需 TTF 字體檔)
$font = __DIR__ . '/fonts/msyh.ttf'; // 微軟雅黑,請自行放置
if (!is_file($font)) {
// 降級:內建字體 (僅 ASCII)
imagestring($img, 5, 20, 10, $code, $txt);
} else {
// 參數:圖片、字體大小、角度、x、y、顏色、字體路徑、文字
imagettftext($img, 20, mt_rand(-10, 10), 15, 30, $txt, $font, $code);
}
// 6. 干擾線
for ($i = 0; $i < 5; $i++) {
imageline($img, 0, mt_rand(0, $height), $width, mt_rand(0, $height), $line);
}
// 7. 噪點
for ($i = 0; $i < 200; $i++) {
imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), $noise);
}
// 8. 輸出
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
?>
<?php
session_start();
header('Content-Type: application/json; charset=utf-8');
$input = trim($_POST['captcha'] ?? '');
$stored = $_SESSION['captcha'] ?? '';
if (strtoupper($input) === strtoupper($stored)) {
echo json_encode(['success' => true, 'msg' => '驗證通過']);
unset($_SESSION['captcha']); // 一次性使用
} else {
echo json_encode(['success' => false, 'msg' => '驗證碼錯誤']);
}
?>
<form id="loginForm">
<input type="text" name="username" placeholder="帳號" required>
<input type="password" name="password" placeholder="密碼" required>
<div class="captcha-row">
<input type="text" name="captcha" placeholder="驗證碼" required maxlength="4">
<img id="captchaImg" src="verify.php" alt="點擊更換" style="cursor:pointer;vertical-align:middle">
</div>
<button type="submit">登入</button>
</form>
<script>
document.getElementById('captchaImg').onclick = () => {
document.getElementById('captchaImg').src = 'verify.php?' + Date.now();
};
document.getElementById('loginForm').onsubmit = async (e) => {
e.preventDefault();
const fd = new FormData(e.target);
const res = await fetch('verify_check.php', {method:'POST', body:fd});
const data = await res.json();
alert(data.msg);
if (data.success) location.href = '/dashboard';
else document.getElementById('captchaImg').click();
};
</script>
msyh.ttf (微軟雅黑) 或其他支援中文的 TTF 字體至 fonts/ 目錄,確保 Web 使用者可讀取。php -m | grep gd 確認已載入,且支援 FreeType (`php -i | grep -i freetype`)。session.cookie_httponly=1, session.cookie_secure=1 (HTTPS), session.use_strict_mode=1。