萬盛學電腦網

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

PHP 實現算術驗證碼:10 以內加減法圖片生成類

前言

傳統字符驗證碼易被 OCR 識別,算術驗證碼(如「3 + 5 = ?」)兼具人類友好與機器識別難度。本文封裝一個 ImageCode 類,自動生成 10 以內加減法算式圖片,答案存入 Session 驗證。

完整類代碼

<?php
class ImageCode {
    private $Jiashu = 0;      // 加數/減數
    private $JianShu = 0;     // 被加數/被減數
    private $YunSuan = '';    // 運算符 +/-
    private $DeShu = 0;       // 答案
    private $String = '';     // 顯示字符串
    private $Img;             // GD 圖片資源
    private $Width = 100;     // 寬度
    private $Height = 50;     // 高度
    private $Ttf = 'Num.ttf'; // 字體文件路徑
    private $Session = 'code';// Session 鍵名

    // 隨機生成算式(保證結果非負)
    private function JiaShu() {
        $this->Jiashu = rand(1, 10);
        $this->JianShu = rand(1, 10);
        if ($this->Jiashu > $this->JianShu) {
            $this->YunSuan = '-';
            $this->DeShu = $this->Jiashu - $this->JianShu;
        } else {
            $this->YunSuan = '+';
            $this->DeShu = $this->Jiashu + $this->JianShu;
        }
    }

    // 公開入口:生成並輸出圖片
    public function Show($W = 100, $H = 50, $T = 'Num.ttf', $Code = 'code') {
        $this->JiaShu();
        $this->String = "{$this->Jiashu}{$this->YunSuan}{$this->JianShu}= ? ";
        $this->Width = $W;
        $this->Height = $H;
        $this->Ttf = $T;
        $this->Session = $Code;

        session_start();
        $_SESSION[$this->Session] = $this->DeShu; // 存儲答案

        $this->Images();
    }

    // 繪製圖片
    private function Images() {
        header('Content-Type: image/png');
        $this->Img = imagecreate($this->Width, $this->Height);
        $bg = imagecolorallocate($this->Img, 255, 255, 255); // 白底
        imagecolortransparent($this->Img, $bg); // 設置透明色

        // 繪制文本(黑色,14px,座標 1,20)
        $textColor = imagecolorallocate($this->Img, 0, 0, 0);
        imagettftext($this->Img, 14, 0, 1, 20, $textColor, $this->Ttf, $this->String);

        $this->EchoImages();
    }

    // 輸出並銷毀
    private function EchoImages() {
        imagepng($this->Img);
        imagedestroy($this->Img);
    }
}

// 使用入口
$ImageCode = new ImageCode();
$ImageCode->Show(130, 35, 'Num.ttf', 'code');

前端調用示例

<img src="captcha.php" id="captcha" alt="驗證碼" style="cursor:pointer" onclick="this.src='captcha.php?'+Math.random()" />
<input type="text" name="verify" placeholder="請輸入計算結果" />
<script>
document.getElementById('captcha').onclick = function() {
    this.src = 'captcha.php?' + Date.now(); // 點擊刷新
};
</script>

驗證邏輯(表單處理頁)

session_start();
if (isset($_POST['verify'])) {
    $answer = intval($_POST['verify']);
    $correct = $_SESSION['code'] ?? null;
    if ($answer === $correct) {
        echo "驗證通過!";
        unset($_SESSION['code']); // 一次性使用
    } else {
        echo "答案錯誤,請重試。";
    }
}

增強建議(生產環境必做)

  • 幹擾元素:添加隨機線條、噪點、背景圖片(imageline、imagesetpixel)。
  • 字體隨機化:準備多個 TTF 字體,隨機選擇字體、大小、角度、顏色。
  • Session 安全:使用 session_regenerate_id() 防固定攻擊,HTTPS 下設置 session.cookie_secure=1。
  • 限流:同一 IP 短時間請求驗證碼次數限制。
  • 字體文件:確保 Num.ttf 存在且可讀,或改用內置字體 imagestring(不支持中文)。

總結

算術驗證碼以簡單邏輯實現了「人機好區分、開發低成本」的平衡。結合 GD 庫繪圖與 Session 存儲,幾十行代碼即可構建可用的驗證體系,是中小項目極佳的選擇。

copyright © 萬盛學電腦網 all rights reserved