ThinkPHP 專案中驗證碼無法顯示是常見問題,通常源於 GD 擴充模組未啟用、輸出緩衝衝突、路由/命名空間錯誤或Session 儲存異常。本文提供系統性排查步驟與完整可用代碼。
php -m | grep gd 或 phpinfo() 確認 gd 已載入,php.ini 需啟用 extension=gd (PHP 7.2+) 或 extension=php_gd2.dll (舊版)echo、var_dump、空白行、錯誤訊息session.save_path 目錄存在且可寫,權限正確<?php
namespace app\controller;
use think\Controller;
use think\captcha\Captcha;
class Auth extends Controller
{
public function verify()
{
$config = [
'length' => 4,
'fontSize' => 20,
'useCurve' => true,
'useNoise' => true,
'imageH' => 40,
'imageW' => 120,
'fontttf' => '5.ttf', // 確保字體檔存在
'bg' => [240, 240, 240],
];
$captcha = new Captcha($config);
return $captcha->entry();
}
public function login()
{
if ($this->request->isPost()) {
$code = $this->request->post('verify');
if (!captcha_check($code)) {
$this->error('驗證碼錯誤');
}
// ... 登入邏輯
}
return $this->fetch();
}
}
<form action="{:url('auth/login')}" method="post">
<input type="text" name="username" placeholder="帳號" required>
<input type="password" name="password" placeholder="密碼" required>
<input type="text" name="verify" placeholder="驗證碼" required>
<img id="captcha" src="{:url('auth/verify')}" alt="點擊刷新" style="cursor:pointer; vertical-align:middle">
<button type="submit">登入</button>
</form>
<script>
document.getElementById('captcha').onclick = function() {
this.src = '{:url("auth/verify")}?' + Date.now(); // 防快取
};
</script>
<?php
// 控制器中或驗證器類別
use think\facade\Validate;
$validate = new Validate([
'verify' => 'require|captcha'
]);
if (!$validate->check($this->request->post())) {
$this->error($validate->getError());
}
// 或手動驗證
if (!captcha_check($this->request->post('verify'))) {
$this->error('驗證碼錯誤');
}
?>
| 錯誤現象 | 原因 | 修正 |
|---|---|---|
| 圖片顯示破圖/無法載入 | GD 未安裝、字體檔缺失、輸出前有輸出 | 安裝 GD、檢查 fontttf 路徑、ob_clean() 前置 |
| 永遠驗證失敗 | Session 未啟動、Session 路徑不可寫、驗證碼大小寫敏感 | session_start()、權限 777、captcha_check 預設不區分大小寫 |
| 驗證碼不隨點擊更新 | 瀏覽器快取圖片 URL | 加入時間戳查詢字串 ?t=timestamp |
| 生產環境正常、本地異常 | PHP 版本差異、php.ini 設定不同 | 對齊 PHP 版本、比對 phpinfo() GD 區塊 |
<?php
class SimpleCaptcha {
public static function generate($len = 4, $w = 120, $h = 40) {
$code = '';
$chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
for ($i = 0; $i < $len; $i++) {
$code .= $chars[random_int(0, strlen($chars)-1)];
}
$_SESSION['captcha_code'] = strtolower($code);
$im = imagecreatetruecolor($w, $h);
$bg = imagecolorallocate($im, 240, 240, 240);
imagefill($im, 0, 0, $bg);
// 干擾線
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($im, rand(150,200), rand(150,200), rand(150,200));
imageline($im, rand(0,$w), rand(0,$h), rand(0,$w), rand(0,$h), $color);
}
// 文字
for ($i = 0; $i < $len; $i++) {
$color = imagecolorallocate($im, rand(0,100), rand(0,100), rand(0,100));
$x = 15 + $i * 24;
$y = rand(5, 15);
imagestring($im, 5, $x, $y, $code[$i], $color);
}
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
public static function check($input) {
return strtolower(trim($input)) === ($_SESSION['captcha_code'] ?? '');
}
}