三文件協作:
ValidationCode.class.php —— 核心生成類(GD 繪圖)imgcode.php —— 輸出圖片、寫入 Sessiondemo.php —— 前端頁面、JS 刷新、表單驗證
class ValidationCode {
private $width, $height, $codenum;
public $checkcode; // 生成的驗證碼字符串
private $checkimage; // GD 圖片資源
private $disturbColor; // 干擾像素顏色
public function __construct($width = 80, $height = 20, $codenum = 4) {
$this->width = $width;
$this->height = $height;
$this->codenum = $codenum;
}
public function outImg() {
$this->outputHeader();
$this->generateCode();
$this->createImage();
$this->setDisturbPixels();
$this->drawCode();
imagepng($this->checkimage);
imagedestroy($this->checkimage);
}
private function outputHeader() {
header('Content-Type: image/png');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
}
private function generateCode() {
// 取 MD5 前 N 位,大寫,排除易混淆字符可自行擴展
$this->checkcode = strtoupper(substr(md5(mt_rand()), 0, $this->codenum));
}
private function createImage() {
$this->checkimage = imagecreate($this->width, $this->height);
$bg = imagecolorallocate($this->checkimage, 255, 255, 255); // 白底
$border = imagecolorallocate($this->checkimage, 0, 0, 0); // 黑框
imagefilledrectangle($this->checkimage, 0, 0, $this->width-1, $this->height-1, $bg);
imagerectangle($this->checkimage, 0, 0, $this->width-1, $this->height-1, $border);
}
private function setDisturbPixels() {
for ($i = 0; $i < 200; $i++) {
$color = imagecolorallocate($this->checkimage, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imagesetpixel($this->checkimage, mt_rand(2, $this->width-2), mt_rand(2, $this->height-2), $color);
}
}
private function drawCode() {
for ($i = 0; $i < $this->codenum; $i++) {
$color = imagecolorallocate($this->checkimage, mt_rand(0,255), mt_rand(0,128), mt_rand(0,255));
$x = floor($this->width / $this->codenum) * $i + mt_rand(-2, 2); // 輕微抖動
$y = mt_rand(2, $this->height - 15);
imagechar($this->checkimage, mt_rand(5, 8), $x, $y, $this->checkcode[$i], $color);
}
}
public function __destruct() {
unset($this->width, $this->height, $this->codenum);
}
}
session_start(); require_once 'ValidationCode.class.php'; $vc = new ValidationCode(100, 30, 4); // 寬100、高30、4位 $vc->outImg(); $_SESSION['validation_code'] = $vc->checkcode; // 大寫存儲
session_start();
// 處理提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = strtoupper(trim($_POST['code'] ?? ''));
if ($input === ($_SESSION['validation_code'] ?? '')) {
echo '驗證通過!';
} else {
echo '驗證碼錯誤';
}
exit;
}
?>
點擊刷新驗證碼演示
登錄驗證
imgcode.php?' + Date.now() 確保每次請求 URL 唯一,繞過瀏覽器/代理緩存。後端也發送了 Cache-Control: no-store 雙重保險。
生成時 strtoupper,驗證時 strtoupper,避免大小寫不敏感導致的用戶困擾。
imageline/imagearc 干擾線imagettftext + TTF 字體替代內置字體,效果更佳session_regenerate_id(true)
// JS
$('#loginForm').submit(function(e) {
e.preventDefault();
$.post('verify.php', {code: $('#code').val()}, function(res) {
if (res.ok) location.href = '/dashboard';
else { alert(res.msg); $('#captcha').click(); }
}, 'json');
});
// verify.php
session_start();
echo json_encode([
'ok' => strtoupper($_POST['code']) === ($_SESSION['validation_code'] ?? ''),
'msg' => '驗證碼錯誤'
]);
基於 GD 庫的驗證碼生成是 PHP 經典技能。本實現涵蓋圖片生成、Session 綁定、前端點擊刷新、表單驗證完整鏈路。生產環境建議結合字符集優化、TTF 字體、干擾曲線、請求限流等措施,並在關鍵業務(登錄、註冊、支付)部署。現代項目亦可考慮 Google reCAPTCHA v3 / hCaptcha / 行為驗證 等零交互方案提升用戶體驗。