驗證碼是 Web 表單防刷的第一道防線。本文提供一個功能完整、代碼清晰的 ValidateCode 類,支援 TTF 字體、隨機背景、干擾線、雪花噪點、字符旋轉與隨機色彩,並解析核心 GD 函數用法,方便二次開發與整合。
| 屬性/方法 | 說明 |
|---|---|
$charset | 字符池,預設排除易混淆字符(0/O, 1/I/l 等) |
$codelen | 驗證碼長度,預設 4 |
$width/$heigth | 圖片尺寸,預設 130x50 |
$font/$fontsize | TTF 字體路徑與大小 |
createCode() | 從字符池隨機生成驗證碼 |
createBg() | 建立真彩畫布並填充隨機淺色背景 |
createFont() | 逐字繪製,支援隨機旋轉、位移、色彩 |
createLine() | 繪製 6 條干擾線 + 100 個雪花噪點 |
outPut() | 輸出 PNG 並銷毀資源 |
doimg() | 公開入口,依序調用上述流程 |
getCode() | 取得小寫驗證碼(供 Session 驗證) |
<?php
class ValidateCode {
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
private $code = '';
private $codelen = 4;
private $width = 130;
private $heigth = 50;
private $img;
private $font;
private $fontsize = 20;
private $fontcolor;
public function __construct() {
// 專案根目錄常數 ROOT_PATH 需自行定義
$this->font = ROOT_PATH . '/font/elephant.ttf';
}
private function createCode() {
$len = strlen($this->charset);
for ($i = 1; $i <= $this->codelen; $i++) {
$this->code .= $this->charset[mt_rand(0, $len - 1)];
}
}
private function createBg() {
$this->img = imagecreatetruecolor($this->width, $this->heigth);
$bgColor = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
imagefilledrectangle($this->img, 0, 0, $this->width, $this->heigth, $bgColor);
}
private function createFont() {
$xStep = $this->width / $this->codelen;
for ($i = 0; $i < $this->codelen; $i++) {
$this->fontcolor = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
$x = $xStep * $i + mt_rand(1, 5);
$y = $this->heigth / 1.4;
$angle = mt_rand(-30, 30);
imagettftext($this->img, $this->fontsize, $angle, $x, $y, $this->fontcolor, $this->font, $this->code[$i]);
}
}
private function createLine() {
// 干擾線
for ($i = 0; $i < 6; $i++) {
$color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->heigth),
mt_rand(0, $this->width), mt_rand(0, $this->heigth), $color);
}
// 雪花噪點
for ($i = 0; $i < 100; $i++) {
$color = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->heigth), '*', $color);
}
}
private function outPut() {
header('Content-type: image/png');
imagepng($this->img);
imagedestroy($this->img);
}
public function doimg() {
$this->createBg();
$this->createCode();
$this->createLine();
$this->createFont(); // 字體繪製在最後,確保在噪點上層
$this->outPut();
}
public function getCode() {
return strtolower($this->code);
}
}
<?php session_start(); require_once 'ValidateCode.class.php'; $vc = new ValidateCode(); $vc->doimg(); // 直接輸出圖片 $_SESSION['captcha'] = $vc->getCode(); // 存入 Session 驗證
<img src="captcha.php" id="captchaImg" onclick="this.src='captcha.php?'+Math.random()" /> <input type="text" name="captcha" />
imagecreatetruecolor():建立真彩色圖像(支援透明度、Alpha 混合)imagecolorallocate():分配顏色索引imagefilledrectangle():填充矩形(背景)imagettftext():使用 TTF 字體繪製文本(支援旋轉、抗鋸齒)imageline()、imagestring():繪製幾何圖形與內建字體字符imagepng():輸出 PNG 格式imagedestroy():釋放記憶體unset($_SESSION['captcha']),限制嘗試次數onclick 附加隨機查詢字串避免快取Securimage、Gregwar/Captcha 等成熟庫這個類代碼精簡、邏輯清晰,適合直接投入專案或作為學習 GD 圖形繪製的教學範例。根據業務需求調整尺寸、字符集、干擾強度即可投產使用。