Using Codeigniter’s Built-in Captcha with Form Validation Library

Using Codeigniter's Built-in Captcha with Form Validation Library

Captchas are the images you use on your forms to keep bots off the bay. Codeigniter gives you a built-in captcha helper which you can use to generate some captchas. Bit confusing part for newbies is using codeigniter’s form validation with built-in captcha. Following is the working example of captcha generation and captcha validation in code igniter.

Controller Test.php

class Test extends CI_Controller {
    public function my_form(){
    $this->form_validation->set_rules('captcha', 'Captcha', 'callback_validate_captcha'); // Described below

    if ($this->form_validation->run() == FALSE) {
        $data['captcha']['image'] = $this->session->userdata("image");
    else {

      print "So, You are not a robot!";
        $data['captcha'] = $this->_generate_captcha();	// Captcha Generated using custom function defined below
        $session_data = array('captcha'	=>  $data['captcha']['word'],
             'image'	  =>  $data['captcha']['image'],
             'filename'   =>	$data['captcha']['filename'] );
  $this->load->view('myform', $data);

function _generate_captcha(){		

    $options = array(
            'img_path'      => './assets/captcha/', // this directory needs to be created to store generated image
            'img_url'       => base_url("assets/captcha"), // absolute path to directory.
            'img_width'     => 200,
            'expiration'    => 7200,
            'word_length'   => 8,
            'font_size'     => 30,
            'img_id'        => 'Imageid',
            'pool'          => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',

            'colors'        => array(
                    'background' => array(255, 255, 255),
                    'border' => array(255, 255, 255),
                    'text' => array(0, 0, 0),
                    'grid' => array(255, 40, 40))

    $captcha =  create_captcha($options);
    return $captcha;

public function validate_captcha(){
    $this->load->library(array("form_validation", "session"));
    if(strtolower($this->input->post('captcha')) != strtolower($this->session->userdata['captcha'])){
      $this->form_validation->set_message('validate_captcha', 'Wrong captcha code');
      return false;
      return true;


View (myform.php)

<form method="post">
<?php print $captcha['image'] ; print form_error('captcha'); ?>
<input name="captcha" placeholder="captcha" type="text">
<button type="submit">Validate Captcha</button>

 You may also download the source code in zip format from here (mirror).



I am a web developer based in Lahore. I spend my days playing with wordpress, code igniter, wide variety of key web projects and frameworks.

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × five =

Translate »