萬盛學電腦網

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

PHP 驗證碼進階實作:傾斜、正弦干擾線、字符黏連與旋轉

驗證碼是區分人機的第一道防線。單純干擾線、噪點已易被 OCR 識別;現代高強度驗證碼結合字體扭曲、字符黏連、隨機旋轉、正弦波干擾線,大幅提升機器識別難度。本文提供完整可用的 PHP 類別實作,支援自訂字體、顏色、尺寸、角度等參數。

驗證碼強度對比

類型特徵機器識別難度人類辨識難度
干擾線/噪點隨機線條、點低(傳統影像處理即可去噪)低
字體扭曲/傾斜仿射變換扭曲字形中(需分割字符再識別)中
字符黏連/重疊字符間距縮小甚至重疊高(字符分割極難)中低(人類整體識別強)
綜合型(本文實作)旋轉+傾斜+黏連+正弦干擾線極高中

完整類別實作:Utils_Caption

<?php
/**
 * 綜合型驗證碼:支援旋轉、傾斜、黏連、正弦干擾線
 * @author 程默 (https://www.cnblogs.com/chengmo)
 */
class Utils_Caption {
    // 可配置屬性
    public $Width = 60;              // 圖片寬(基礎值,實際依字符數自動調整)
    public $Height = 30;             // 圖片高
    public $Length = 4;              // 驗證碼位數
    public $BgColor = '#FFFFFF';     // 背景色
    public $TFonts = ['font.ttf'];   // 字體檔案陣列(需放置於 font/ 目錄)
    public $TFontSize = [17, 20];    // 字體大小範圍 [min, max]
    public $TFontAngle = [-20, 20];  // 旋轉角度範圍 [min, max]
    public $Chars = '0123456789';    // 字符集(可加入字母)
    public $FontColors = ['#f36161','#6bc146','#5368bd']; // 字體顏色池
    public $TPadden = 0.75;          // 字符間距係數(<1 產生黏連效果)
    public $Txbase = 5;              // X 軸邊距
    public $Tybase = 5;              // Y 軸邊距
    public $TLine = true;            // 是否繪製正弦干擾線

    private $Code = [];              // 產生的驗證碼資料
    private $Image = null;           // GD 圖片資源

    /** 產生驗證碼字符陣列 */
    public function RandRSI() {
        $this->TFontAngle = range($this->TFontAngle[0], $this->TFontAngle[1]);
        $this->TFontSize  = range($this->TFontSize[0],  $this->TFontSize[1]);
        $arr = [];
        $charlen = strlen($this->Chars) - 1;
        $font = dirname(__FILE__) . '/font/' . $this->TFonts[0];

        for ($i = 0; $i < $this->Length; $i++) {
            $char       = $this->Chars[rand(0, $charlen)];
            $angle      = $this->TFontAngle[rand(0, count($this->TFontAngle)-1)];
            $fontsize   = $this->TFontSize[rand(0, count($this->TFontSize)-1)];
            $fontcolor  = $this->FontColors[rand(0, count($this->FontColors)-1)];
            $bound      = $this->_calculateTextBox($fontsize, $angle, $font, $char);
            $arr[]      = [$fontsize, $angle, $fontcolor, $char, $font, $bound];
        }
        $this->Code = $arr;
        return implode('', array_column($arr, 3)); // 回傳純字串供 Session 儲存
    }

    /** 繪製並輸出圖片 */
    public function Draw() {
        if (empty($this->Code)) $this->RandRSI();
        $codes = $this->Code;
        list($width, $height) = $this->_getImageWH($codes);
        $this->Width = $width; $this->Height = $height;

        $this->Image = imagecreate($width, $height);
        $bg = $this->_getColor2($this->_getColor($this->BgColor));
        imagefilledrectangle($this->Image, 0, 0, $width, $height, $bg);

        $basex = $this->Txbase;
        $color = null;
        foreach ($codes as $v) {
            $color = $this->_getColor2($this->_getColor($v[2]));
            imagettftext($this->Image, $v[0], $v[1], $basex, $v[5]['height'], $color, $v[4], $v[3]);
            $basex += $v[5]['width'] * $this->TPadden - $v[5]['left'];
        }

        if ($this->TLine) $this->_writeSinLine($color, $basex);

        header('Content-Type: image/png');
        imagepng($this->Image);
        imagedestroy($this->Image);
    }

    /** 計算字符邊界框 */
    private function _calculateTextBox($font_size, $font_angle, $font_file, $text) {
        $box = imagettfbbox($font_size, $font_angle, $font_file, $text);
        $min_x = min($box[0], $box[2], $box[4], $box[6]);
        $max_x = max($box[0], $box[2], $box[4], $box[6]);
        $min_y = min($box[1], $box[3], $box[5], $box[7]);
        $max_y = max($box[1], $box[3], $box[5], $box[7]);
        return [
            'left'   => ($min_x >= -1) ? -abs($min_x + 1) : abs($min_x + 2),
            'top'    => abs($min_y),
            'width'  => $max_x - $min_x,
            'height' => $max_y - $min_y,
            'box'    => $box
        ];
    }

    /** 計算整體圖片寬高 */
    private function _getImageWH($data) {
        $w = $this->Txbase; $h = 0;
        foreach ($data as $v) {
            $w += $v[5]['width'] * $this->TPadden - $v[5]['left'];
            $h = max($h, $v[5]['height']);
        }
        return [max($w, $this->Width), max($h, $this->Height)];
    }

    /** 繪製正弦波干擾線 */
    private function _writeSinLine($color, $w) {
        $img = $this->Image; $h = $this->Height;
        $h1 = rand(-5, 5); $h2 = rand(-1, 1);
        $w2 = rand(10, 15); $h3 = rand(4, 6);
        for ($i = -$w/2; $i < $w/2; $i += 0.1) {
            $y = $h/$h3 * sin($i/$w2) + $h/2 + $h1;
            imagesetpixel($img, $i + $w/2, $y, $color);
            if ($h2) imagesetpixel($img, $i + $w/2, $y + $h2, $color);
        }
    }

    /** 顏色解析輔助 */
    private function _getColor($color) {
        return [hexdec($color[1].$color[2]), hexdec($color[3].$color[4]), hexdec($color[5].$color[6])];
    }
    private function _getColor2($rgb) {
        return imagecolorallocate($this->Image, $rgb[0], $rgb[1], $rgb[2]);
    }
}

使用範例

<?php
session_start();
require_once 'Utils_Caption.php';

$captcha = new Utils_Caption();
$captcha->Length = 5;                    // 5 位數
$captcha->Chars  = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; // 排除易混淆字符
$captcha->TFontSize = [18, 22];
$captcha->TFontAngle = [-25, 25];
$captcha->TPadden = 0.6;                 // 更緊湊,增強黏連

$code = $captcha->RandRSI();
$_SESSION['captcha_code'] = strtoupper($code); // 儲存供驗證
$captcha->Draw();

前端驗證邏輯

<?php // verify.php
session_start();
if (strtoupper($_POST['captcha']) === ($_SESSION['captcha_code'] ?? '')) {
    echo '驗證通過';
    unset($_SESSION['captcha_code']); // 一次性使用
} else {
    echo '驗證碼錯誤';
}

字體檔案準備

在腳本同目錄建立 font/ 目錄,放入一個 TTF 字體檔(如 `font.ttf`,粗體無襯線字體效果最佳)。開源字體推薦:Noto Sans、Source Sans Pro。

效能與部署提示

  • GD 庫需啟用 FreeType 支援(`--with-freetype-dir` 編譯或 `extension=gd` 確認 `FreeType Support => enabled`)。
  • 高流量場景建議:預生成驗證碼圖片池或使用 Redis 快取 驗證碼,減少即時 GD 繪圖 CPU 消耗。
  • 無障礙考量:務必提供音頻驗證碼或簡單算術題作為備選方案。

這套驗證碼結合了現代反自動化識別的多項技術,部署簡單、參數靈活,適合中小型專案直接採用。大型系統建議評估引入 Google reCAPTCHA v3 / hCaptcha 等行為分析型方案,兼顧安全與使用者體驗。

copyright © 萬盛學電腦網 all rights reserved