驗證碼類 ImageCode 隨機生成一道加法或減法算式(如 7 + 3 = ? 或 9 - 4 = ?),將運算結果存入 Session,再用 GD 庫繪製成 PNG 圖片輸出。
<?php
class ImageCode {
private $Jiashu = 0; // 加數/減數
private $JianShu = 0; // 被加數/被減數
private $YunSuan = ''; // 運算符 + 或 -
private $DeShu = 0; // 結果
private $String = ''; // 顯示字串
private $Img; // 圖片資源
private $Width = 100;
private $Height = 50;
private $Ttf = 'Num.ttf'; // 字體檔案
private $Session = 'code';
private function JiaShu() {
header('Content-type: image/png');
$this->Jiashu = rand(1, 10);
$this->JianShu = rand(1, 10);
$this->YunSuan = $this->Jiashu > $this->JianShu ? '-' : '+';
$this->DeShu = $this->YunSuan === '-'
? $this->Jiashu - $this->JianShu
: $this->Jiashu + $this->JianShu;
}
public function Show($W = 100, $H = 50, $T = 'Num.ttf', $Code = 'code') {
$this->JiaShu();
$this->String = "{$this->Jiashu}{$this->YunSuan}{$this->JianShu}= ?";
$this->Width = $W; $this->Height = $H; $this->Ttf = $T; $this->Session = $Code;
session_start();
$_SESSION[$this->Session] = $this->DeShu;
$this->Images();
}
private function Images() {
$this->Img = imagecreate($this->Width, $this->Height);
$bg = imagecolorallocate($this->Img, 255, 255, 255);
imagecolortransparent($this->Img, $bg);
$black = imagecolorallocate($this->Img, 0, 0, 0);
imagettftext($this->Img, 14, 0, 1, 20, $black, $this->Ttf, $this->String);
$this->EchoImages();
}
private function EchoImages() {
imagepng($this->Img);
imagedestroy($this->Img);
}
}
// 使用示例
$ImageCode = new ImageCode;
$ImageCode->Show(130, 35, 'Num.ttf', 'code');
<img src="captcha.php" id="captcha" onclick="this.src='captcha.php?'+Math.random()" />
點擊圖片即可刷新驗證碼。
session_start();
if ($_POST['captcha'] == $_SESSION['code']) {
// 驗證通過
} else {
// 驗證失敗
}
Num.ttf 需放在可讀取路徑,或改用內建字體 imagestring 免依賴 TTF。