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

<?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>



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

Comments

Share

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 »