$_SESSION['code'] 供驗證。<?php
function generateCaptcha($length = 4, $width = 100, $height = 30) {
// 1. 產生隨機碼
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= dechex(mt_rand(0, 15)); // 0-9 a-f
}
$_SESSION['captcha_code'] = $code;
// 2. 建立畫布
$img = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($img, 250, 250, 250);
imagefill($img, 0, 0, $white);
// 3. 邊框
$gray = imagecolorallocate($img, 196, 196, 196);
imagerectangle($img, 0, 0, $width - 1, $height - 1, $gray);
// 4. 干擾線 (6 條)
for ($i = 0; $i < 6; $i++) {
$color = imagecolorallocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color);
}
// 5. 噪點 (50 個 *)
for ($i = 0; $i < 50; $i++) {
$color = imagecolorallocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagestring($img, 1, mt_rand(1, $width - 5), mt_rand(1, $height - 5), '*', $color);
}
// 6. 繪製驗證碼字元
for ($i = 0; $i < $length; $i++) {
$color = imagecolorallocate($img, mt_rand(0, 102), mt_rand(0, 102), mt_rand(0, 102));
$x = $i * $width / $length + mt_rand(1, 10);
$y = mt_rand(1, $height / 2);
imagestring($img, 5, $x, $y, $code[$i], $color);
}
// 7. 輸出
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
}
// 使用範例
session_start();
generateCaptcha(4, 120, 40);
<img src="captcha.php" id="captchaImg" style="cursor:pointer" title="點擊刷新">
<input type="text" name="captcha" placeholder="輸入驗證碼">
<script>
document.getElementById('captchaImg').onclick = function() {
this.src = 'captcha.php?' + Date.now(); // 防快取
};
</script>
session_start();
if (strtolower($_POST['captcha']) !== strtolower($_SESSION['captcha_code'])) {
die('驗證碼錯誤');
}
// 通過,執行業務邏輯...
imagettftext() 取代 imagestring(),效果更佳。此函數提供開箱即用的 GD 驗證碼生成,涵蓋畫布建立、噪點干擾、字元繪製、Session 存儲、PNG 輸出全流程。可直接放入 captcha.php 供前端呼叫。