將驗證碼生成邏輯封裝為可高度配置的類別,支援自訂字元集、尺寸、字型、顏色、干擾線/點、字元旋轉角度等。
class Image {
// 畫布設定
public $width = 85;
public $height = 25;
public $code_len = 4;
public $code_str = "329832983DSDSKDSLKQWEWQ2lkfDSFSDjfdsfdsjwlkfj93290KFDSKJFDSOIDSLK";
public $bg_color = '#DCDCDC';
public $font_size = 16;
public $font = 'font.ttf';
public $font_color = '#000000';
private $img;
public $code;
// 產生隨機驗證碼
public function create_code() {
$code = '';
for ($i = 0; $i < $this->code_len; $i++) {
$code .= $this->code_str[mt_rand(0, strlen($this->code_str)-1)];
}
return $this->code = $code;
}
// 主流程:建立畫布 → 寫字元 → 干擾 → 輸出
public function getImage() {
$img = imagecreatetruecolor($this->width, $this->height);
$bg = $this->hex2rgb($this->bg_color);
$bg_color = imagecolorallocate($img, $bg[0], $bg[1], $bg[2]);
imagefill($img, 0, 0, $bg_color);
$this->img = $img;
$this->create_font(); // 寫入驗證碼字元
$this->create_pix(); // 干擾線/點
$this->show_code(); // 輸出圖片
}
// 寫入字元(使用 TTF 字型支援旋轉)
public function create_font() {
$this->create_code();
$x = $this->width / $this->code_len;
for ($i = 0; $i < $this->code_len; $i++) {
$color = imagecolorallocate($this->img, mt_rand(0,100), mt_rand(0,150), mt_rand(0,200));
imagettftext($this->img, $this->font_size, mt_rand(-30, 30),
$x*$i + mt_rand(3,6), mt_rand($this->height/1.2, $this->height),
$color, $this->font, $this->code[$i]);
}
}
// 干擾點與線
public function create_pix() {
$color = $this->hex2rgb($this->font_color);
$pix_color = imagecolorallocate($this->img, $color[0], $color[1], $color[2]);
for ($i=0; $i<100; $i++) {
imagesetpixel($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), $pix_color);
}
for ($j=0; $j<4; $j++) {
imagesetthickness($this->img, mt_rand(1,2));
imageline($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height),
mt_rand(0,$this->width), mt_rand(0,$this->height), $pix_color);
}
}
// 取得驗證碼(大寫)供驗證用
public function getCode() {
return strtoupper($this->code);
}
// 輸出 PNG
private function show_code() {
header("Content-Type: image/png");
imagepng($this->img);
imagedestroy($this->img);
}
// 輔助:16進位顏色轉 RGB 陣列
private function hex2rgb($hex) {
return [
hexdec(substr($hex, 1, 2)),
hexdec(substr($hex, 3, 2)),
hexdec(substr($hex, 5, 2))
];
}
}
// captcha.php require 'Image.class.php'; session_start(); $captcha = new Image(); $captcha->width = 120; $captcha->height = 40; $captcha->code_len = 4; $captcha->font = __DIR__ . '/fonts/Verdana.ttf'; $captcha->getImage(); $_SESSION['captcha_code'] = $captcha->getCode();
// 驗證邏輯
if (strtoupper($_POST['captcha']) !== $_SESSION['captcha_code']) {
die('驗證碼錯誤');
}
| 屬性 | 預設值 | 說明 |
|---|---|---|
| width | 85 | 畫布寬度 |
| height | 25 | 畫布高度 |
| code_len | 4 | 驗證碼字元數 |
| code_str | 長字串 | 字元池(可移除易混淆字元) |
| bg_color | #DCDCDC | 背景色 |
| font_size | 16 | 字體大小 |
| font | font.ttf | TTF 字型路徑(必須存在) |
| font_color | #000000 | 干擾線/點顏色基準 |
物件導向封裝讓驗證碼生成邏輯可複用、可配置、易維護,專案中只需實例化並設定屬性即可獲得專業級驗證碼圖片。