驗證碼是 Web 應用程式防止自動化腳本濫用的關鍵機制。本文提供一個功能完整的 PHP 類別方法,示範如何使用 GD 函式庫生成高強度的驗證碼圖片,包含隨機干擾弧線、雜點噪點、TrueType 字體傾斜渲染,並透過 Session 儲存驗證碼供後續驗證。
function image3($length = 4, $type = 'png', $width = 180, $height = 60, $fontface = 'fpnf.ttf', $verifyName = 'verify') {
// 產生隨機驗證碼字串(需自行實作 rand_string 方法)
$code = $this->rand_string($length, 4);
// 動態調整寬度,確保每字元至少 25px
$width = ($length * 25) > $width ? $length * 25 : $width;
// 將驗證碼存入 Session(此處原碼變數 $randval 應為 $code)
$authCode = new Zend_Session_Namespace('Auth_Code');
$authCode->imagecode = $code;
// 建立真彩色畫布
$im = imagecreatetruecolor($width, $height);
$borderColor = imagecolorallocate($im, 100, 100, 100); // 邊框色
$bkcolor = imagecolorallocate($im, 250, 250, 250); // 背景色
imagefill($im, 0, 0, $bkcolor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
// 干擾弧線
for ($i = 0; $i < 15; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
}
// 雜點噪點
for ($i = 0; $i < 255; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor);
}
// 確認字體檔案路徑
if (!is_file($fontface)) {
$fontface = dirname(__FILE__) . '/' . $fontface;
}
// 逐字元繪製
for ($i = 0; $i < $length; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); // 深色系
$codex = substr($code, $i, 1);
imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $fontface, $codex);
}
$this->output($im, $type);
}
// 輸出圖片並銷毀資源
function output($im, $type = 'png') {
header('Content-type: image/' . $type);
$ImageFun = 'Image' . $type;
$ImageFun($im);
imagedestroy($im);
}
原始碼中 `$authCode->imagecode = $randval;` 變數未定義,實務上應改為 `$authCode->imagecode = $code;` 以儲存真正的驗證碼字串。
預設使用 `fpnf.ttf`,請確認該字體檔案存在於腳本同目錄,或提供絕對路徑。若無中文字體需求,英文數字驗證碼即可運作。
字元旋轉角度範圍 `-60° ~ 60°`、字級 `16~20pt`、Y 軸位置 `30~35px` 隨機化,配合干擾弧線與雜點,可有效對抗 OCR 識別。
此實作展示了 PHP GD 庫進階繪圖技巧,透過多層干擾與 TrueType 字體隨機化渲染,可產出兼具安全性與可讀性的驗證碼圖片。開發者可依專案需求調整干擾密度、色彩範圍或字體風格,構建專屬的驗證碼防護體系。