October 27, 2014

October 27, 2014
In this article, we are going to discuss about How to add captcha to your website in CodeIgniter (CI). In CodeIgniter (CI), we have an in-built helper to add captcha named "Captcha Helper".  Using Captcha helper, we can easily integrate Captcha into our application. To use this helper we have to load it.
At first we have to create a table for Captcha in our database. It contains four fields.

id => INT, word => TEXT, ip => TEXT, time=>TEXT

Then use the following code.

$this->load->helper('url');
$this->load->helper('string');
$this->load->helper('captcha');

Then declare an array with the following values. This array contains the values needed to create Captcha.

$rand = random_string('numeric', 8);
$vals = array(
'word'     => $rand,
'img_path'   => './captcha/',
'img_url'    => './captcha/',
'img_width'  => '150',
'img_height' => 60,
'expiration' => 7200
);
$cap = create_captcha($vals);  // Generates Capthca

I would like to explain the values mentioned in this array. First 'word' mentions the random value to be displayed. I generated a random number of length 8 and assigned it to the Captcha word. Next is 'img_path'. This decides the path to the file where generated Captcha image is to be stored. 'img_url' defines the path to be used when displaying the image. As name specifies 'img_width','img_height','expiration' denotes the image width, height and expiration time of Captcha.

Next we have to insert the generated Captcha value into table.

$this->load->model('common_model');
$this->common_model->insert_captcha($cap);
$data['cap'] = $cap;
$this->load->view('welcome_message',$data);

Add the following in your View file.

<p><h3>Enter the following Number</h3></p>
<form action="<?php echo base_url().'index.php/welcome/check' ?>" method="post">
<?php echo $cap['image']; ?><br>
<input type="text" name="captcha" placeholder="Type here.."/>
<br><br>
<input type="submit" value="submit">
</form>

Captcha values are inserted into the table and View is called.

Then on form submission, use the following code.

$expiration = time()-7200; // Two hour limit
$ip = $_SERVER['REMOTE_ADDR'];
$this->load->database();
$this->db->query("DELETE FROM captcha WHERE time < ".$expiration);

// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip = ? AND time > ?";
$binds = array($_POST['captcha'], $ip, $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";
}
else{
echo "Matches";
}

0 comments:

Post a Comment