codeigniter CAPTCHA Helper Complete example


Here is an example of usage with a database. On the page where the CAPTCHA will be shown you'll have something like this:

$vals = array(
    'img_path'    => './captcha/',
    'img_url'    => ''

$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);

echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';

Then, on the page that accepts the submission you'll have something like this:

// 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)
    echo "You must submit the word that appears in the image";