Using the Captcha Plugin in Codeigniter with Form Validation
Codeigniter ships with a captcha plugin that is not documented in the User Guide. The code is commented well and has examples though. This is how I used the captcha plugin with form validation to help stop spam on a basic contact form, without using a table in my database. It seems unecessary to add this call to MySQL when we could easily just store it in session.
First, our controllers method. This handles setting up our form validation rules, building the captcha, and storing the captcha data in a session for retrieval later. We have a rule for our captcha field that is a callback to our validation function, “cinput_check”.
<?php
function contact()
{
$this->load->library('session');
$this->load->plugin('captcha');
/* Setup captcha defaults */
$captcha_defaults = array(
'img_path' => './images/captcha/',
'img_url' => 'http://site.com/images/captcha/',
'img_width' => 200,
'img_height' => 50,
);
$this->load->library('validation');
/* include your additional form field rules here as well */
$rules['cinput'] = "callback_cinput_check";
$this->validation->set_rules($rules);
/* include your additional form fields here as well */
$fields['cinput'] = "Captcha";
$this->validation->set_fields($fields);
if ($this->validation->run() == FALSE)
{
/* since validation failed, generate new captcha
data and update the session */
$cap = create_captcha($captcha_defaults);
$form_tpl['captcha'] = $cap['image'];
$this->session->set_userdata(array('cinput'=>$cap['word']));
$this->load->view('site/contact_us', $form_tpl);
}
else
{
/* Continue to process form */
}
}
?>
This is our call back function, and validates the posted captcha value against the generated value stored in session. For some reason checking $str against the value in $this->session was not working, so I simply bypassed that and used the value from the input handler.
<?php
function cinput_check($str)
{
if ($this->input->post('cinput') != $this->session->userdata('cinput'))
{
$this->validation->_error_messages['cinput_check'] = 'Incorrect Captcha characters.';
return FALSE;
}
else
{
return TRUE;
}
}
?>
The form is just a generic form, but here is what the captcha field looks like for reference:
<p><?php print $captcha; ?><br />
<label for="Captcha">Type in the code:</label>
<input type="text" name="cinput" id="Captcha" value="" /></p>
For more information on Codeigniter check out their extremely well documented User Guide.









Comments