msyhbd.ttf)渲染漢字<img src="captcha.php"><?php
// 設置內容類型
header('Content-Type: image/png');
// 常用漢字字符池(約 300 字)
$charset = '的一是不了能好都然沒日於起還發成事只作當想看文無開手十用主行方又如前所本見經頭面公同三已老從動兩長知民樣現分將外但身些與高意進把法此實回二理美點月明其種聲全工己話兒者向情部正名定女問力機給等幾很業最間新什打便位因重被走電四第門相次東政海口使教西再平真聽世氣信北少關並內加化由卻代軍產入先山五太水萬市眼體別處總才場師書比住員九笑性通目華報立馬命張活難神數件安表原車白應路期叫死常提感金何更反合放做系計或司利受光王果親界及今京務制解各任至清物台象記邊共風戰干接它許八特覺望直服毛林題建南度統色字請交愛讓';
// 創建畫布
$width = 100;
$height = 45;
$im = imagecreatetruecolor($width, $height);
// 背景色
$bgColor = imagecolorallocate($im, 200, 200, 200);
imagefill($im, 0, 0, $bgColor);
// 字體文件路徑(需確保文件存在且可讀)
$fontPath = __DIR__ . '/fonts/msyhbd.ttf';
if (!file_exists($fontPath)) {
// 回退方案:使用內置字體生成數字驗證碼
imagestring($im, 5, 20, 15, rand(1000, 9999), imagecolorallocate($im, 0, 0, 0));
imagepng($im);
imagedestroy($im);
exit;
}
$len = mb_strlen($charset, 'UTF-8');
$x = 0;
for ($i = 0; $i < 4; $i++) {
// 隨機顏色(較深色系)
$color = imagecolorallocate($im, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
// 隨機水平偏移
$x += $i * 10 + mt_rand(5, 15);
// 隨機選取一個漢字
$char = mb_substr($charset, mt_rand(0, $len - 1), 1, 'UTF-8');
// 隨機字體大小、角度、垂直位置
$fontSize = mt_rand(14, 18);
$angle = mt_rand(-15, 15);
$y = mt_rand(22, 28);
// 繪製文字
imagettftext($im, $fontSize, $angle, $x, $y, $color, $fontPath, $char);
}
// 可選:添加干擾線/點
// for ($i = 0; $i < 5; $i++) {
// imageline($im, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), imagecolorallocate($im, mt_rand(150,200), mt_rand(150,200), mt_rand(150,200)));
// }
imagepng($im);
imagedestroy($im);
?>
<img id="captcha" src="captcha.php" alt="驗證碼" style="cursor:pointer; vertical-align:middle;" onclick="this.src='captcha.php?'+Math.random()" title="點擊刷新">
<input type="text" name="captcha" placeholder="輸入圖中漢字">
<?php
session_start();
// 生成驗證碼時存入 Session
// 在 captcha.php 中添加:
// $_SESSION['captcha_chars'] = $generatedChars; // 需修改生成代碼返回字符串
// 驗證提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = trim($_POST['captcha'] ?? '');
$stored = $_SESSION['captcha_chars'] ?? '';
// 不區分大小寫,去除空格
if (mb_strtolower($input) === mb_strtolower($stored)) {
echo "驗證通過";
unset($_SESSION['captcha_chars']); // 一次性使用
} else {
echo "驗證碼錯誤";
}
}
?>
這個中文驗證碼實現簡單易懂,適合學習 GD 庫繪圖與 Session 驗證流程,生產環境建議採用成熟的第三方驗證碼服務。