首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 中文驗證碼類:GD 繪圖、干擾點、TrueType 字體渲染

     編輯:PHP 綜合知識

類別功能

  • 可配置圖片尺寸、背景色、干擾點數量、字體大小/顏色
  • 支援中文字符 (需 TrueType 字體檔 .ttc/.ttf)
  • 驗證碼存入 $_SESSION['code'] 供後端驗證
  • 輸出 PNG 格式,適合 `` 嵌入

完整類別代碼

<?php
class Captcha {
    // 可配置屬性
    public $width      = 160;
    public $height     = 40;
    public $bgColor    = [223, 225, 227];  // RGB
    public $noiseColor = [242, 168, 162];
    public $textColor  = [50, 30, 100];    // 文字色 (深色系)
    public $fontSize   = 20;
    public $fontFile   = 'C:/Windows/Fonts/simsun.ttc'; // 依伺服器實際路徑調整
    public $length     = 4;                // 驗證碼長度
    public $charset    = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; // 排除易混淆字符
    public $noiseCount = 200;

    private $image;
    private $code = '';

    public function generate() {
        // 1. 建立畫布
        $this->image = imagecreatetruecolor($this->width, $this->height);
        $bg = imagecolorallocate($this->image, ...$this->bgColor);
        imagefill($this->image, 0, 0, $bg);

        // 2. 產生隨機碼
        $chars = str_split($this->charset);
        for ($i = 0; $i < $this->length; $i++) {
            $this->code .= $chars[array_rand($chars)];
        }
        $_SESSION['captcha_code'] = $this->code;

        // 3. 繪製干擾點
        $noiseColor = imagecolorallocate($this->image, ...$this->noiseColor);
        for ($i = 0; $i < $this->noiseCount; $i++) {
            imagesetpixel($this->image, mt_rand(0, $this->width), mt_rand(0, $this->height), $noiseColor);
        }

        // 4. 繪製文字 (逐字元隨機旋轉/位移)
        $textColor = imagecolorallocate($this->image, ...$this->textColor);
        $x = 10;
        for ($i = 0; $i < $this->length; $i++) {
            $angle = mt_rand(-15, 15);
            $y = mt_rand($this->fontSize + 2, $this->height - 5);
            imagettftext($this->image, $this->fontSize, $angle, $x, $y, $textColor, $this->fontFile, $this->code[$i]);
            $x += $this->fontSize + mt_rand(2, 6);
        }

        // 5. 輸出
        header('Content-Type: image/png');
        imagepng($this->image);
        imagedestroy($this->image);
    }

    // 靜態驗證方法
    public static function check($input) {
        return isset($_SESSION['captcha_code']) &&
               strtoupper($input) === strtoupper($_SESSION['captcha_code']);
    }
}

// captcha.php (獨立檔案)
session_start();
require_once 'Captcha.php';
$captcha = new Captcha();
$captcha->generate();

前端嵌入

<form method="post" action="submit.php">
  <img src="captcha.php" id="captchaImg" alt="點擊更換" style="cursor:pointer;vertical-align:middle" />
  <a href="javascript:void(0)" onclick="document.getElementById('captchaImg').src='captcha.php?'+Date.now()">看不清?換一張</a><br>
  <input type="text" name="captcha" maxlength="4" required />
  <input type="submit" value="送出" />
</form>

後端驗證

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (Captcha::check($_POST['captcha'])) {
        echo "驗證通過,處理業務邏輯...";
    } else {
        echo "驗證碼錯誤";
    }
}
?>

進階強化

  • 干擾線:imageline() 畫隨機曲線
  • 背景圖片:imagecreatefromjpeg() 載入圖片做背景
  • Session 防暴力:限制驗證次數、加入 CSRF Token
  • 無障礙替代:提供語音驗證碼選項
  • 字體路徑跨平台:Linux 常見 /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf,建議專案內置字體檔並用相對路徑

現代替代方案

  • Google reCAPTCHA v3 / hCaptcha:行為分析、無感驗證、極高安全性
  • Turnstile (Cloudflare):隱私優先、免費無限量
  • Geetest / 騰訊防水牆:滑塊/點選/語序驗證,中文環境優化
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved