CodeIgniter (CI) 內建的 captcha 輔助函數提供了快速生成圖形驗證碼的能力,但預設將圖片存為文件而非直接輸出二進制流,使用時需注意路徑配置與清理策略。本文詳細演示配置步驟、代碼示例及常見問題解決。
php -m | grep gd)。captcha/ 目錄,並設置可寫權限(chmod 777 captcha)。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 是否能在瀏覽器直接訪問圖片文件。expiration 參數只在 create_captcha() 調用時觸發清理,高流量建議配合 cron 定期清理 captcha/ 目錄。word 為字母數字混合、增加干擾線、使用 TTF 字體、或改用 Gregwar/Captcha 等更強大的第三方庫。CI 的 captcha 輔助函數適合快速原型與中小專案。生產環境建議: