[CodeIgniter] CAPTCHA 輔助函式

在 CodeIgniter 要做圖形驗證,可以簡單使用 CAPTCHA 這個輔助函式。

首先像這樣載入。
  1. $this->load->helper('captcha');  

再做一下設定就可以用了。

  1. $vals = array(   
  2.         'word'          => 'Random word',   
  3.         'img_path'      => './captcha/',   
  4.         'img_url'       => 'http://example.com/captcha/',   
  5.         'font_path'     => './path/to/fonts/texb.ttf',   
  6.         'img_width'     => '150',   
  7.         'img_height'    => 30,   
  8.         'expiration'    => 7200,   
  9.         'word_length'   => 8,   
  10.         'font_size'     => 16,   
  11.         'img_id'        => 'Imageid',   
  12.         'pool'          => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',   
  13.   
  14.         // White background and border, black text and red grid   
  15.         'colors'        => array(   
  16.                 'background' => array(255, 255, 255),   
  17.                 'border' => array(255, 255, 255),   
  18.                 'text' => array(0, 0, 0),   
  19.                 'grid' => array(255, 40, 40)   
  20.         )   
  21. );   
  22.   
  23. $cap = create_captcha($vals);   
  24. var_dump($cap );  

有幾點在設定時要注意。

驗證碼函式需要 GD 圖像函式庫。
只有 img_path 與 img_url 是必填的。
假設沒有填 **word**,函式會自動生成一個隨機的 ASCII 字串,當然你也可以從你自己準備的文字庫當中隨機挑選。
如果你沒有標明字型檔的路徑,將會使用醜醜的預設字型。
“captcha” 資料夾必須是可以寫入的。
expiration (以秒數計) 標明出驗證碼圖示過多久之後會被刪除,預設是兩小時。
word_length 預設為 8,**pool** 預設為 ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’。
font_size 預設為 16,GD 字型有大小限制。如果要使用更大的字體請選用其他字型。
img_id 將是驗證碼圖示的 id。
如果任一 colors 內的值不見了,將會以預設值代替。

再來可以利用 session 儲存驗證碼,減少資料庫的負擔。
  1. $this->session->unset_userdata('captchaCode');   
  2. $this->session->set_userdata('captchaCode',$captcha['word']);  




參考:
CAPTCHA 輔助函式
How to Implement Captcha in CodeIgniter using Captcha Helper

留言

Unknown寫道…
感謝大大分享,可否跟大大要個連絡方式,因為小弟觀看大大對於CI有很多的Api教學。