Using Codeigniter’s Built-in Captcha with Form Validation

Codeigniter’s Built-in Captcha with Form Validation

Why Use Codeigniter’s Built-in Captcha

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 codeigniter.

Controller

Test.php

<?php class Test extends CI_Controller { public function my_form(){ if($this->input->post()){
      $this->load->library("form_validation");
    $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 {
      if(!$this->session->has_userdata('filename'))
        redirect("Test/my_form");

      if(file_exists(BASEPATH."../assets/captcha/".$this->session->userdata['filename']))
        unlink(BASEPATH."../assets/captcha/".$this->session->userdata['filename']);
      
      session_destroy();
      print "So, You are not a robot!";
      exit; 
    }
  }
  else{
        $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->library('session'); 
  $this->session->set_userdata($session_data);	
  }	
  
  $this->load->view('myform', $data);
}


function _generate_captcha(){		
    $this->load->library('image_lib');
    $this->load->helper('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;
    }
    else{
      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>
</form>



Download the compressed source code from here (mirror).

 

You can reach Waqas Yousaf through twitter @wiqi.
Share

Waqas Yousaf is Freelance Web Developer, Blogger, start-up manager and Co-Founder of wishdd.com.

Comments

  1. I have noticed you don’t monetize your website, don’t waste your traffic, you
    can earn additional cash every month because you’ve got
    high quality content.

  2. Apart from view and controller, you also have to create model for implement captcha in codeigniter, like done here: **filtered** Or creating model is optional and it can be done without? Can you confirm.

Leave a Reply

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

twelve − 8 =