已有無驗證碼的查詢頁面,需加入驗證碼驗證:用戶輸入查詢條件+驗證碼提交 → 校驗碼正確 → 執行查詢並顯示結果;校驗失敗 → 提示錯誤不查詢。
採用 index.php 同時承擔兩個角色:
<?php
session_start();
// 1. 生成驗證碼存入 Session
$_SESSION['vcode'] = substr(md5(rand()), 0, 4);
// 2. 處理 POST 提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (strtoupper($_POST['vcode']) === strtoupper($_SESSION['vcode'])) {
// 驗證通過 → 執行查詢邏輯
$keyword = $_POST['keyword'];
$results = queryDatabase($keyword); // 自定義查詢函數
// 輸出結果...
} else {
$error = '驗證碼錯誤';
}
}
// 3. 輸出 HTML 表單(包含錯誤提示、刷新驗證碼 JS)
?>
<form method="post">
查詢關鍵字:<input name="keyword"><br>
驗證碼:<input name="vcode" size=4>
<img id="captcha" src="vcode.php" onclick="this.src='vcode.php?'+Math.random()">
<button type="submit">查詢</button>
</form>
<?php if(isset($error)) echo "<p style='color:red'>$error</p>"; ?>
<?php
session_start();
header('Content-Type: image/png');
$im = imagecreatetruecolor(80, 30);
$bg = imagecolorallocate($im, 230, 230, 230);
imagefill($im, 0, 0, $bg);
$code = $_SESSION['vcode'];
for ($i=0; $i<4; $i++) {
$color = imagecolorallocate($im, rand(0,100), rand(0,100), rand(0,100));
imagettftext($im, 18, rand(-15,15), 15+$i*15, 22, $color, 'font.ttf', $code[$i]);
}
// 干擾線
for ($j=0; $j<5; $j++) {
imageline($im, rand(0,80), rand(0,30), rand(0,80), rand(0,30), imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)));
}
imagepng($im);
imagedestroy($im);
$_SESSION['vcode'],校驗時讀取比對。strtoupper() 比對。unset($_SESSION['vcode']) 防止重放。gregwar/captcha)而非手寫 GD 代碼。