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

PHP 實現加減法驗證碼(GD 庫生成圖片)

     編輯:PHP 相關知識

核心思路

驗證碼類 ImageCode 隨機生成一道加法或減法算式(如 7 + 3 = ? 或 9 - 4 = ?),將運算結果存入 Session,再用 GD 庫繪製成 PNG 圖片輸出。

完整類代碼

<?php
class ImageCode {
    private $Jiashu = 0;      // 加數/減數
    private $JianShu = 0;     // 被加數/被減數
    private $YunSuan = '';    // 運算符 + 或 -
    private $DeShu = 0;       // 結果
    private $String = '';     // 顯示字串
    private $Img;             // 圖片資源
    private $Width = 100;
    private $Height = 50;
    private $Ttf = 'Num.ttf'; // 字體檔案
    private $Session = 'code';

    private function JiaShu() {
        header('Content-type: image/png');
        $this->Jiashu = rand(1, 10);
        $this->JianShu = rand(1, 10);
        $this->YunSuan = $this->Jiashu > $this->JianShu ? '-' : '+';
        $this->DeShu = $this->YunSuan === '-' 
            ? $this->Jiashu - $this->JianShu 
            : $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() {
        $this->Img = imagecreate($this->Width, $this->Height);
        $bg = imagecolorallocate($this->Img, 255, 255, 255);
        imagecolortransparent($this->Img, $bg);
        $black = imagecolorallocate($this->Img, 0, 0, 0);
        imagettftext($this->Img, 14, 0, 1, 20, $black, $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" onclick="this.src='captcha.php?'+Math.random()" />

點擊圖片即可刷新驗證碼。

驗證邏輯(後端)

session_start();
if ($_POST['captcha'] == $_SESSION['code']) {
    // 驗證通過
} else {
    // 驗證失敗
}

優化建議

  • 增加干擾線、噪點、字體旋轉提高安全性。
  • 字體檔 Num.ttf 需放在可讀取路徑,或改用內建字體 imagestring 免依賴 TTF。
  • Session 驗證碼建議設置短過期時間,驗證後立即銷毀防重放。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved