首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CodeIgniter 框架 CAPTCHA 輔助函數生成驗證碼完整教程

     編輯:PHP 相關知識

CodeIgniter 框架 CAPTCHA 輔助函數生成驗證碼完整教程

CodeIgniter (CI) 內建的 captcha 輔助函數提供了快速生成圖形驗證碼的能力,但預設將圖片存為文件而非直接輸出二進制流,使用時需注意路徑配置與清理策略。本文詳細演示配置步驟、代碼示例及常見問題解決。

環境準備

  1. 確保 PHP 安裝 GD 庫(php -m | grep gd)。
  2. 在 CI 專案根目錄建立 captcha/ 目錄,並設置可寫權限(chmod 777 captcha)。
  3. 自動載入輔助函數:編輯 application/config/autoload.php,將 'captcha' 加入 $autoload['helper'] 陣列,或在控制器中臨時載入 $this->load->helper('captcha');。

生成驗證碼核心代碼

$config = [
    'word'       => rand(1000, 9999),          // 4 位隨機數字
    'img_path'   => './captcha/',              // 圖片儲存絕對/相對路徑(需可寫)
    'img_url'    => base_url('captcha/'),      // 圖片訪問 URL(需能公開訪問)
    'img_width'  => 150,
    'img_height' => 40,
    'expiration' => 7200,                      // 圖片過期秒數,超時自動清理
    // 'font_path' => './path/to/font.ttf',    // 可選:指定 TTF 字體路徑
];

$cap = create_captcha($config);

// $cap 返回陣列包含:
// 'word'   => 驗證碼字串(需存入 Session 驗證)
// 'time'   => 生成時間戳
// 'image'  => 完整的  標籤 HTML
// 'filename' => 生成的文件名

// 存入 Session 供後續驗證
$this->session->set_userdata('captcha_word', $cap['word']);

// 輸出圖片標籤到視圖
echo $cap['image'];

視圖中顯示與點擊刷新

<!-- 視圖文件 -->
<div id="captcha-box">
    <?php echo $cap['image']; ?>
    <a href="javascript:;" onclick="refreshCaptcha()">看不清?換一張</a>
</div>

<script>
function refreshCaptcha() {
    // 假設控制器有 /captcha/refresh 路由返回新的 image 標籤
    fetch('/captcha/refresh')
        .then(res => res.text())
        .then(html => document.getElementById('captcha-box').innerHTML = html);
}
</script>

驗證邏輯(控制器)

public function verify() {
    $input = $this->input->post('captcha_code');
    $stored = $this->session->userdata('captcha_word');
    
    if (empty($input) || strtolower($input) !== strtolower($stored)) {
        // 驗證失敗
        $this->session->set_flashdata('error', '驗證碼錯誤');
        redirect('form');
    }
    // 驗證通過,清除 Session 防重放
    $this->session->unset_userdata('captcha_word');
    // 繼續業務邏輯...
}

常見問題與優化

  • 圖片不顯示:檢查 img_path 是否真實可寫、img_url 是否能在瀏覽器直接訪問圖片文件。
  • Session 驗證失效:確保開啟 Session、域名一致、未被攔截器清空。
  • 垃圾文件堆積:expiration 參數只在 create_captcha() 調用時觸發清理,高流量建議配合 cron 定期清理 captcha/ 目錄。
  • 安全性增強:可自定義 word 為字母數字混合、增加干擾線、使用 TTF 字體、或改用 Gregwar/Captcha 等更強大的第三方庫。

總結

CI 的 captcha 輔助函數適合快速原型與中小專案。生產環境建議:

  1. 將驗證碼生成邏輯封裝為 Library 或 Service,便於替換實現。
  2. 引入速率限制(如同一 IP 分鐘最多請求 5 次)。
  3. 考慮無障礙訪問,提供語音驗證碼或 hCaptcha/reCAPTCHA 替代方案。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved