首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

PHP 信息查詢頁面接入驗證碼完整實現指南

     編輯:程式設計疑難解答

需求場景

已有無驗證碼的查詢頁面,需加入驗證碼驗證:用戶輸入查詢條件+驗證碼提交 → 校驗碼正確 → 執行查詢並顯示結果;校驗失敗 → 提示錯誤不查詢。

核心思路:同一腳本處理「顯示表單」與「處理提交」

採用 index.php 同時承擔兩個角色:

  • GET 請求:渲染表單、生成驗證碼圖片(存入 Session)。
  • POST 請求:校驗 Session 中的驗證碼 → 通過則查詢數據庫並輸出結果 → 失敗則重顯表單並提示。

關鍵代碼結構

1. 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>"; ?>

2. vcode.php(生成圖片)

<?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);

關鍵點總結

  1. Session 傳遞驗證碼:生成時寫入 $_SESSION['vcode'],校驗時讀取比對。
  2. 大小寫不敏感:建議雙方統一 strtoupper() 比對。
  3. 點擊刷新:`` 避免緩存。
  4. 查詢邏輯放在驗證通過後:不可將查詢與驗證分離到兩個獨立腳本,否則會出現「只校驗不查詢」的問題。

安全增強建議

  • 驗證碼用完即銷毀:unset($_SESSION['vcode']) 防止重放。
  • 加入 CSRF Token 防跨站請求偽造。
  • 生產環境建議使用成熟庫(如 gregwar/captcha)而非手寫 GD 代碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved