ValidateCode 類別封裝了驗證碼生成的完整流程:隨機字元生成、背景繪製、干擾線/雪花繪製、文字渲染、圖片輸出。採用 GD 庫繪圖,支援 TTF 字體,具備良好的可擴展性。
class ValidateCode {
private $charset = 'abcdefghjkmnprstuvwxyzABCDEFGJKMNPRSTUVWXYZ23456789'; // 排除易混淆字元
private $code;
private $codeLen = 4;
private $width = 130;
private $heigh = 50;
private $img;
private $font;
private $fontsize = 20;
public function __construct() {
$this->font = ROOT_PATH . '/font/Chowderhead.ttf';
$this->img = imagecreatetruecolor($this->width, $this->heigh);
}
}
createCode()private function createCode() {
$_len = strlen($this->charset) - 1;
for ($i = 0; $i < $this->codeLen; $i++) {
$this->code .= $this->charset[mt_rand(0, $_len)];
}
}
使用 mt_rand 而非 rand 取得更好隨機性,字元集已排除 i,l,o,q,0,1 等易混淆字元。
createBg()private function createBg() {
$color = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
imagefilledrectangle($this->img, 0, $this->heigh, $this->width, 0, $color);
}
RGB 值限制在 157-255 區間,產生淡色背景確保文字可讀性。
createFont()private function createFont() {
$_x = $this->width / $this->codeLen;
$_y = $this->heigh / 2;
for ($i = 0; $i < $this->codeLen; $i++) {
$color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
imagettftext($this->img, $this->fontsize, mt_rand(-30, 30),
$_x * $i + mt_rand(3, 5), $_y + mt_rand(2, 4),
$color, $this->font, $this->code[$i]);
}
}
關鍵參數:
createLine()// 15 條深色干擾線
for ($i = 0; $i < 15; $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->heigh),
mt_rand(0,$this->width), mt_rand(0,$this->heigh), $color);
}
// 150 個淡色雪花點 (# 字元)
for ($i = 0; $i < 150; $i++) {
$color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagestring($this->img, mt_rand(1, 5), mt_rand(0,$this->width), mt_rand(0,$this->heigh), '#', $color);
}
private function outPut() {
header('Content-Type: image/png');
imagepng($this->img);
imagedestroy($this->img);
}
public function getCode() {
return strtolower($this->code); // 統一轉小寫便於驗證
}
<?php
define('ROOT_PATH', dirname(__FILE__));
require_once ROOT_PATH . '/includes/ValidateCode.class.php';
$_vc = new ValidateCode();
echo $_vc->doImg();
<?php
require substr(dirname(__FILE__), 0, -7) . '/init.inc.php';
$_vc = new ValidateCode();
echo $_vc->doImg();
$_SESSION['ValidateCode'] = $_vc->getCode();
<label>
<img src="../config/code.php"
onclick="javascript:this.src='../config/code.php?tm='+Math.random();" />
</label>
問題:專案整合時驗證碼圖片無法顯示(顯示錯誤圖示或亂碼)
原因:輸出緩衝區已有內容(如 BOM、空白字元、前置輸出),導致 header() 失效
解決方案:
header() 前呼叫 ob_clean() 清空緩衝(但可能影響其他輸出)參考原文 3.8 節,含完整 97 行程式碼,可直接複製使用。