Codeigniter has a nice CAPTCHA function (would be nice if we did not need them) which I used on the contact page. To use this you include the captcha helper, include a table in the database, and then just check the return value against what is expected. The system handles the cleaning. When inserting a new record you have to save the IP address, time, and the word to be displayed (I used the default). In the form validation function I use a call back to handle this.
$this->load->helper('captcha');
$vals = array( 'img_path' => './images/', 'img_url' => base_url() . 'images/' ); $cap = create_captcha($vals); $data['cap'] = $cap; $sqlData = array( 'captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word'] ); $query = $this->db->insert_string('captcha', $sqlData); $this->db->query($query);
// the call back $this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|callback_checkCaptcha');
function checkCaptcha() { // First, delete old captchas $expiration = time()-7200; // Two hour limit $this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration); // Then see if a captcha exists: $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) { $this->form_validation->set_message('checkCaptcha', 'CAPTCHA must match input value'); return FALSE; } return TRUE; }
first test
second test
third test