萬盛學電腦網

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

PHP 驗證碼類 ValidateCode 完整解析與實作

類別架構概覽

ValidateCode 類別封裝了驗證碼生成的完整流程:隨機字元生成、背景繪製、干擾線/雪花繪製、文字渲染、圖片輸出。採用 GD 庫繪圖,支援 TTF 字體,具備良好的可擴展性。

核心屬性與構造函數

class ValidateCode {
    private $charset = 'abcdefghjkmnprstuvwxyzABCDEFGJKMNPRSTUVWXYZ23456789'; // 排除易混淆字元
    private $code;
    private $codeLen = 4;
    private $width = 130;
    private $heigh = 50;
    private $img;
    private $font;
    private $fontsize = 20;

    public function __construct() {
        $this->font = ROOT_PATH . '/font/Chowderhead.ttf';
        $this->img = imagecreatetruecolor($this->width, $this->heigh);
    }
}

關鍵方法詳解

1. 隨機碼生成 createCode()

private function createCode() {
    $_len = strlen($this->charset) - 1;
    for ($i = 0; $i < $this->codeLen; $i++) {
        $this->code .= $this->charset[mt_rand(0, $_len)];
    }
}

使用 mt_rand 而非 rand 取得更好隨機性,字元集已排除 i,l,o,q,0,1 等易混淆字元。

2. 背景繪製 createBg()

private function createBg() {
    $color = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
    imagefilledrectangle($this->img, 0, $this->heigh, $this->width, 0, $color);
}

RGB 值限制在 157-255 區間,產生淡色背景確保文字可讀性。

3. 文字渲染 createFont()

private function createFont() {
    $_x = $this->width / $this->codeLen;
    $_y = $this->heigh / 2;
    for ($i = 0; $i < $this->codeLen; $i++) {
        $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
        imagettftext($this->img, $this->fontsize, mt_rand(-30, 30),
            $_x * $i + mt_rand(3, 5), $_y + mt_rand(2, 4),
            $color, $this->font, $this->code[$i]);
    }
}

關鍵參數:

  • X 軸:平均分配寬度 + 隨機偏移 (3-5px)
  • Y 軸:垂直置中 + 隨機偏移 (2-4px)
  • 旋轉角度:-30° 到 30° 隨機
  • 文字顏色:深色系 (0-156) 與背景形成對比

4. 干擾元素 createLine()

// 15 條深色干擾線
for ($i = 0; $i < 15; $i++) {
    $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
    imageline($this->img, mt_rand(0,$this->width), mt_rand(0,$this->heigh),
              mt_rand(0,$this->width), mt_rand(0,$this->heigh), $color);
}

// 150 個淡色雪花點 (# 字元)
for ($i = 0; $i < 150; $i++) {
    $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
    imagestring($this->img, mt_rand(1, 5), mt_rand(0,$this->width), mt_rand(0,$this->heigh), '#', $color);
}

5. 輸出與取得驗證碼

private function outPut() {
    header('Content-Type: image/png');
    imagepng($this->img);
    imagedestroy($this->img);
}

public function getCode() {
    return strtolower($this->code); // 統一轉小寫便於驗證
}

實際應用範例

獨立測試頁

<?php
define('ROOT_PATH', dirname(__FILE__));
require_once ROOT_PATH . '/includes/ValidateCode.class.php';
$_vc = new ValidateCode();
echo $_vc->doImg();

專案整合(code.php)

<?php
require substr(dirname(__FILE__), 0, -7) . '/init.inc.php';
$_vc = new ValidateCode();
echo $_vc->doImg();
$_SESSION['ValidateCode'] = $_vc->getCode();

前端刷新機制

<label>
    <img src="../config/code.php" 
         onclick="javascript:this.src='../config/code.php?tm='+Math.random();" />
</label>

常見問題與解決

問題:專案整合時驗證碼圖片無法顯示(顯示錯誤圖示或亂碼)

原因:輸出緩衝區已有內容(如 BOM、空白字元、前置輸出),導致 header() 失效

解決方案:

  • 確保 PHP 檔案無 BOM、無前後空白
  • 在 header() 前呼叫 ob_clean() 清空緩衝(但可能影響其他輸出)
  • 最佳做法:驗證碼單獨檔案、無任何前置輸出、UTF-8 無 BOM 編碼

完整類別程式碼

參考原文 3.8 節,含完整 97 行程式碼,可直接複製使用。

copyright © 萬盛學電腦網 all rights reserved