CAPTCHA 輔助函數
驗證碼輔助函數提供一些產生驗證碼相關函數。
載入輔助函數
輔助函數使用下列方式載入:
$this->load->helper('captcha');
可用的函數如下:
create_captcha($data)
傳入一個您定義的陣列函數值來產生驗證碼,函數會回傳產生驗證碼圖片鎮列資料。
[array]
(
'image' => IMAGE TAG
'time' => TIMESTAMP (in microtime)
'word' => CAPTCHA WORD
)
"image" 值為實際 image 標籤:
<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />
"time" 值為 micro timestamp 用來當作驗證碼圖片檔明,但是不含副檔名。例如就像: 1139612155.3422
"word" 值為圖片上的驗證碼, 假如您沒有設定它,函數將會隨機選取字串(random string)。
使用驗證碼補助函數
載入後,產生驗證碼就如同下面程式碼:
$vals = array(
'word' => 'Random word',
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/',
'font_path' => './path/to/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
echo $cap['image'];
- 驗證碼函數需要 GD 的套件函式庫。
- 只需要 img_path 跟 img_url 就可以產生驗證碼
- 假如 word 欄位沒有填寫,此函數會自動幫您產生隨機字串(ASCII string)。 或者是您可以放入自行產生的隨機函式庫。
- 假如您沒有實際設定字型的路徑,系統將會用預設 GD 字型。
- "captcha" 目錄必須是要可以寫入的 (666, or 777)
- "expiration" 值(秒) 代表驗證碼圖片可以存在資料夾多久,超過時間就必須移除。預設值是兩小時。
新增資料庫
驗證函數為了防止使用者送出違法資料, 您需要將 create_captcha() 回傳的陣列值資料存放到資料庫。然後當使用者送出資料時,您必須從資料庫驗證資料是否過期。
底下為資料表欄位格式:
CREATE TABLE captcha (
captcha_id bigint(13) unsigned NOT NULL auto_increment,
captcha_time int(10) unsigned NOT NULL,
ip_address varchar(16) default '0' NOT NULL,
word varchar(20) NOT NULL,
PRIMARY KEY `captcha_id` (`captcha_id`),
KEY `word` (`word`)
);
使用資料庫請參考底下範例。顯示認証碼圖片頁面,你會得到底下程式碼:
$this->load->helper('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';
然後, 此頁面會接受前端傳送的資料,程式碼如下:
// 第一步, 刪除舊有驗證碼資料
$expiration = time()-7200; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// 然後驗證是否存在資料:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}