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

PHP 驗證碼類實現:支援干擾線、噪點、TTF 字體與隨機色彩

     編輯:PHP 相關知識

從零構建生產級 PHP 驗證碼類:完整代碼與設計解析

驗證碼是 Web 表單防刷的第一道防線。本文提供一個功能完整、代碼清晰的 ValidateCode 類,支援 TTF 字體、隨機背景、干擾線、雪花噪點、字符旋轉與隨機色彩,並解析核心 GD 函數用法,方便二次開發與整合。

類結構總覽

屬性/方法說明
$charset字符池,預設排除易混淆字符(0/O, 1/I/l 等)
$codelen驗證碼長度,預設 4
$width/$heigth圖片尺寸,預設 130x50
$font/$fontsizeTTF 字體路徑與大小
createCode()從字符池隨機生成驗證碼
createBg()建立真彩畫布並填充隨機淺色背景
createFont()逐字繪製,支援隨機旋轉、位移、色彩
createLine()繪製 6 條干擾線 + 100 個雪花噪點
outPut()輸出 PNG 並銷毀資源
doimg()公開入口,依序調用上述流程
getCode()取得小寫驗證碼(供 Session 驗證)

完整類代碼

<?php
class ValidateCode {
    private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
    private $code = '';
    private $codelen = 4;
    private $width = 130;
    private $heigth = 50;
    private $img;
    private $font;
    private $fontsize = 20;
    private $fontcolor;

    public function __construct() {
        // 專案根目錄常數 ROOT_PATH 需自行定義
        $this->font = ROOT_PATH . '/font/elephant.ttf';
    }

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

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

    private function createFont() {
        $xStep = $this->width / $this->codelen;
        for ($i = 0; $i < $this->codelen; $i++) {
            $this->fontcolor = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
            $x = $xStep * $i + mt_rand(1, 5);
            $y = $this->heigth / 1.4;
            $angle = mt_rand(-30, 30);
            imagettftext($this->img, $this->fontsize, $angle, $x, $y, $this->fontcolor, $this->font, $this->code[$i]);
        }
    }

    private function createLine() {
        // 干擾線
        for ($i = 0; $i < 6; $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->heigth),
                      mt_rand(0, $this->width), mt_rand(0, $this->heigth), $color);
        }
        // 雪花噪點
        for ($i = 0; $i < 100; $i++) {
            $color = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
            imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->heigth), '*', $color);
        }
    }

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

    public function doimg() {
        $this->createBg();
        $this->createCode();
        $this->createLine();
        $this->createFont(); // 字體繪製在最後,確保在噪點上層
        $this->outPut();
    }

    public function getCode() {
        return strtolower($this->code);
    }
}

使用範例

<?php
session_start();
require_once 'ValidateCode.class.php';

$vc = new ValidateCode();
$vc->doimg(); // 直接輸出圖片
$_SESSION['captcha'] = $vc->getCode(); // 存入 Session 驗證

前端調用

<img src="captcha.php" id="captchaImg" onclick="this.src='captcha.php?'+Math.random()" />
<input type="text" name="captcha" />

核心 GD 函數速查

  • imagecreatetruecolor():建立真彩色圖像(支援透明度、Alpha 混合)
  • imagecolorallocate():分配顏色索引
  • imagefilledrectangle():填充矩形(背景)
  • imagettftext():使用 TTF 字體繪製文本(支援旋轉、抗鋸齒)
  • imageline()、imagestring():繪製幾何圖形與內建字體字符
  • imagepng():輸出 PNG 格式
  • imagedestroy():釋放記憶體

安全與擴展建議

  1. Session 防暴力:驗證後立即 unset($_SESSION['captcha']),限制嘗試次數
  2. 字體多樣化:準備多款 TTF,每次隨機挑選,提高識別難度
  3. 點擊刷新:前端 onclick 附加隨機查詢字串避免快取
  4. 無障礙備選:提供語音驗證碼或 honeypot 隱藏欄位
  5. 效能:高併發下可預先生成圖片池,或改用 Securimage、Gregwar/Captcha 等成熟庫

這個類代碼精簡、邏輯清晰,適合直接投入專案或作為學習 GD 圖形繪製的教學範例。根據業務需求調整尺寸、字符集、干擾強度即可投產使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved