萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

ThinkPHP 驗證碼不顯示問題排查與解決方案

ThinkPHP 專案中驗證碼無法顯示是常見問題,通常源於 GD 擴充模組未啟用、輸出緩衝衝突、路由/命名空間錯誤或Session 儲存異常。本文提供系統性排查步驟與完整可用代碼。

快速診斷清單

  1. GD 擴充模組:執行 php -m | grep gd 或 phpinfo() 確認 gd 已載入,php.ini 需啟用 extension=gd (PHP 7.2+) 或 extension=php_gd2.dll (舊版)
  2. 檔案編碼:驗證碼控制器檔案必須為 UTF-8 無 BOM,BOM 會導致圖片輸出前有隱形字元
  3. 輸出緩衝:驗證碼輸出前不得有任何 echo、var_dump、空白行、錯誤訊息
  4. Session 可寫入:session.save_path 目錄存在且可寫,權限正確

完整實作範例 (ThinkPHP 5.1/6.0)

1. 控制器驗證碼動作

<?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();
    }
}

2. 模板引用驗證碼

<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>

3. 驗證邏輯 (驗證碼驗證)

<?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 區塊

進階:自定義驗證碼類別 (無 ThinkPHP 內建)

<?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'] ?? '');
    }
}
copyright © 萬盛學電腦網 all rights reserved