利用 PHP GD 擴展繪製簡單數字驗證碼,儲存於 Session 供後續驗證。
<?php
// 必須啟動 Session
if (!isset($_SESSION)) {
session_start();
header('Cache-control: private');
}
// 建立 65x20 像素畫布
$width = 65;
$height = 20;
$image = imagecreate($width, $height);
// 背景色
$bg_color = imagecolorallocate($image, 0x33, 0x66, 0xFF);
imagefilledrectangle($image, 0, 0, $width, $height, $bg_color);
// 產生 5 位隨機字串
$text = random_text(5); // 需自行實作 random_text()
// 計算文字置中座標
$font = 5;
$x = imagesx($image) / 2 - strlen($text) * imagefontwidth($font) / 2;
$y = imagesy($image) / 2 - imagefontheight($font) / 2;
// 繪製文字
$fg_color = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
imagestring($image, $font, $x, $y, $text, $fg_color);
// 存入 Session
$_SESSION['captcha'] = $text;
// 輸出圖片
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
<?php
session_start();
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo '驗證通過';
} else {
echo '驗證碼錯誤';
}
?>
imagettftext())實現傾斜、變形效果。gregwar/captcha。簡易驗證碼適合低風險場景,高安全需求請採用成熟庫或第三方驗證服務(如 reCAPTCHA)。