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