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

PHP 驗證碼類:完全可定制的驗證碼生成解決方案

     編輯:PHP 綜合知識

簡介

在 Web 開發中,驗證碼是防止機器人惡意提交表單、註冊或登錄的常用手段。本文提供一個功能完善、高度可定制的 PHP 驗證碼類 Authnum,支援多種字符類型、干擾點、干擾線、Y 軸隨機偏移以及背景顏色自定義,滿足不同安全等級的需求。

核心特性

  • 字符類型靈活:支援大小寫字母混合、純小寫、純大寫、純數字四種模式
  • 防識別增強:可選啟用干擾點、干擾線、字符 Y 軸隨機位移
  • 外觀可定制:背景顏色、圖片尺寸、驗證碼長度皆可通過屬性或構造函數設置
  • Session 自動存儲:生成的驗證碼自動寫入 $_SESSION['an'],方便前端驗證

類結構速覽

class Authnum {
    // 屬性
    private $im, $im_width, $im_height, $len;
    private $randnum, $y, $randcolor;
    public $red = 238, $green = 238, $blue = 238; // 預設淺灰背景
    public $ext_num_type = ''; // 字符類型:''=混合, 1=小寫, 2=大寫, 3=數字
    public $ext_pixel = false; // 干擾點
    public $ext_line = false;  // 干擾線
    public $ext_rand_y = true; // Y軸隨機

    // 方法
    public function __construct($len=4, $im_width='', $im_height=25);
    public function set_bgcolor();
    public function get_randnum();
    public function get_y();
    public function get_randcolor();
    public function set_ext_pixel();
    public function set_ext_line();
    public function create(); // 生成並輸出圖片
}

使用示例

<?php
require_once 'Authnum.class.php';

$an = new Authnum(4, 60, 25); // 4位,寬60,高25
$an->ext_num_type = '';       // 混合模式
$an->ext_pixel = true;        // 開啟干擾點
$an->ext_line = false;        // 關閉干擾線
$an->ext_rand_y = true;       // 開啟Y軸隨機
$an->green = 200;             // 調整背景綠色分量
$an->create();                // 輸出 PNG 圖片
?>

前端驗證邏輯

表單提交時,只需比對 $_SESSION['an'] 與用戶輸入的驗證碼值即可:

if (strtolower($_SESSION['an']) === strtolower($_POST['captcha_input'])) {
    // 驗證通過
} else {
    // 驗證失敗
}

注意事項

  • 需啟用 PHP GD 擴展
  • 生成圖片前不可有任何輸出,否則會導致圖片損壞
  • 生產環境建議開啟干擾線與干擾點,提高破解難度
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved