封裝一個可配置的 Captcha 類,支援:寬高、字元數、Session 鍵名、隨機背景色、干擾像素、字元隨機位置/大小/顏色。使用極簡:new Captcha()->create() 直接輸出圖片。
class Captcha {
private $width = 80, $height = 20, $charNum = 4;
public $code; // 生成的驗證碼
private $img; // 圖片資源
private $sessionKey = 'captcha_code';
public function __construct() {
if (session_status() === PHP_SESSION_NONE) session_start();
}
public function config($width = 80, $height = 20, $charNum = 4, $sessionKey = 'captcha_code') {
$this->width = $width;
$this->height = $height;
$this->charNum = $charNum;
$this->sessionKey = $sessionKey;
return $this; // 鏈式調用
}
public function create() {
header('Content-Type: image/png');
$this->generateCode();
$this->createImage();
$this->drawDisturb();
$this->drawCode();
imagepng($this->img);
imagedestroy($this->img);
$_SESSION[$this->sessionKey] = $this->code;
}
private function generateCode() {
$this->code = strtoupper(substr(md5(rand()), 0, $this->charNum));
}
private function createImage() {
$this->img = imagecreate($this->width, $this->height);
$white = imagecolorallocate($this->img, 255, 255, 255);
$black = imagecolorallocate($this->img, 0, 0, 0);
imagefilledrectangle($this->img, 0, 0, $this->width-1, $this->height-1, $white);
imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1, $black);
}
private function drawDisturb() {
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($this->img, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($this->img, rand(2, $this->width-2), rand(2, $this->height-2), $color);
}
}
private function drawCode() {
$charW = $this->width / $this->charNum;
for ($i = 0; $i < $this->charNum; $i++) {
$color = imagecolorallocate($this->img, rand(0,255), rand(0,128), rand(0,255));
$x = $charW * $i + rand(2, 5);
$y = rand(0, $this->height - 15);
imagechar($this->img, rand(5, 8), $x, $y, $this->code[$i], $color);
}
}
}
// captcha.php (單獨檔案) require 'Captcha.php'; new Captcha()->config(100, 30, 4)->create();
<!-- 表單頁面 --> <img src="captcha.php" id="captchaImg" onclick="this.src='captcha.php?'+Date.now()" style="cursor:pointer"> <input name="captcha" placeholder="點擊圖片刷新">
// 驗證邏輯
session_start();
if (strtoupper($_POST['captcha']) !== $_SESSION['captcha_code']) {
die('驗證碼錯誤');
}
// 通過後清除,防重放
unset($_SESSION['captcha_code']);
imagettftext() + 多款字體 + 旋轉角度 + 扭曲,大幅提高 OCR 識別難度。session_regenerate_id(true) 登入後重生成 ID,設定 session.cookie_httponly=1、session.cookie_secure=1 (HTTPS)。