利用 GD 庫生成包含隨機字符的圖片,將字符存入 Session,用戶提交時比對。機器難以識別扭曲、干擾線、噪點的圖片,從而防止自動化腳本惡意註冊。
captcha.php<?php
session_start();
// 1. 生成 4 位隨機數字
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= random_int(0, 9); // 比 rand() 更安全
}
// 存入 Session
$_SESSION['captcha_code'] = $code;
// 2. 創建畫布
$width = 80; $height = 30;
$im = imagecreatetruecolor($width, $height); // 真彩色畫布
// 3. 分配顏色
$bg = imagecolorallocate($im, 220, 220, 220); // 淺灰背景
$textColor = imagecolorallocate($im, 0, 0, 0); // 黑色文字
$noiseColor = imagecolorallocate($im, 150, 150, 150); // 噪點顏色
// 4. 填充背景
imagefill($im, 0, 0, $bg);
// 5. 繪製干擾線 (隨機 3 條)
for ($i = 0; $i < 3; $i++) {
imageline($im,
random_int(0, $width), random_int(0, $height),
random_int(0, $width), random_int(0, $height),
$noiseColor
);
}
// 6. 繪製干擾像素點 (隨機 50 個)
for ($i = 0; $i < 50; $i++) {
imagesetpixel($im, random_int(0, $width), random_int(0, $height), $noiseColor);
}
// 7. 繪製驗證碼字符 (隨機位置、字體大小)
$fontSize = 5; // 內置字體 1-5
$x = 10;
for ($i = 0; $i < 4; $i++) {
$y = random_int(2, 10);
$char = $code[$i];
imagestring($im, $fontSize, $x, $y, $char, $textColor);
$x += random_int(15, 20); // 隨機間距
}
// 8. 輸出圖片並銷毀資源
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
register.php<form method="post" action="verify.php">
<div>
<label>驗證碼:</label>
<input type="text" name="captcha" required style="width:60px;">
<img src="captcha.php" id="captchaImg" alt="點擊刷新" style="cursor:pointer; vertical-align:middle;" title="點擊刷新">
</div>
<button type="submit">註冊</button>
</form>
<script>
// 點擊圖片刷新驗證碼
document.getElementById('captchaImg').onclick = function() {
this.src = 'captcha.php?' + Date.now(); // 防緩存
};
</script>
verify.php<?php
session_start();
function fail($msg) {
exit("<script>alert('$msg'); history.back();</script>");
}
// 1. 檢查提交
if (empty($_POST['captcha'])) fail('請輸入驗證碼');
// 2. 比對 (不區分大小寫可用 strtolower)
if (strtolower($_POST['captcha']) !== strtolower($_SESSION['captcha_code'])) {
fail('驗證碼錯誤');
}
// 3. 驗證通過,執行註冊邏輯...
echo '驗證通過,處理註冊...';
// 註冊業務代碼...
?>
<?php
session_start();
// 1. 清空 $_SESSION
$_SESSION = [];
// 2. 刪除 Session Cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// 3. 銷毀 Session
session_destroy();
echo '已登出';
?>