Pages

Captcha in Codeigniter with session

Friday, March 2, 2012
In this tutorial I will show you how to use the the codeigniter captcha helper. I use the session to save the captcha data instead of database.

Configuration

Download the CI latest version form codeigniter.com. Extract and rename as ci_captcha.

Open application/config/database.php, and change the following database configuration to fit your mysql configuration.

$config['hostname'] = “localhost”;

$config['username'] = “myusername”;

$config['password'] = “mypassword”;

$config['database'] = “mydatabase”;

$config['dbdriver'] = “mysql”;

Then open application/config/config.php

$config['base_url'] = ‘http://localhost/ci_captcha/’;

$config['encryption_key'] = '1234';

Open application/config/autoload.php

$autoload['libraries'] = array('database’,'session');

and

$autoload['helper'] = array(’form’);

Open application/config/routes.php, change default controller to home controller that we’ll create later on this tutorial.

$route['default_controller'] = ‘home’;

The last thing we need to do for this step is create a folder called captcha under the ci_captcha folder.

Creating Database table

We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `message` (
`id` INT( 50 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 50 ) NOT NULL ,
`message` TEXT NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

Controller

Create a blank document in the controller file (application -> controller) and name it home.php, in the document add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  $this->load->model('home_model');
 }
 public function index()
 {
  $this->load->helper('captcha');
  $vals = array(
     'img_path' => './captcha/',
     'img_url' => 'http://localhost/ci_captcha/captcha/'
     );
  $cap = create_captcha($vals);
  $data = array(
     'captcha_time' => $cap['time'],
     'ip_address' => $this->input->ip_address(),
     'word' => $cap['word']
     );
  $this->session->set_userdata($data);
  $data['cap_img']=$cap['image'];
  $this->load->view('form_view',$data);
 }
 public function add_message()
 {
  $this->load->library('form_validation');
  // field name, error message, validation rules
  $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[3]');
  $this->form_validation->set_rules('message', 'Message', 'trim|required|xss_clean');
  $this->form_validation->set_rules('captcha', 'Security Code', 'trim|required|callback_check_captcha');
  if($this->form_validation->run() == FALSE)
  {
   $this->index();
  }
  else
  {
   $this->home_model->add_message();
  }
 }
 public function check_captcha()
 {
  $expiration = time()-7200; // Two hour limit
  $cap=$this->input->post('captcha');
  if($this->session->userdata('word')== $cap 
   AND $this->session->userdata('ip_address')== $this->input->ip_address()
   AND $this->session->userdata('captcha_time')> $expiration)
  {
   return true;
  }
  else{
   $this->form_validation->set_message('check_captcha', 'Security number does not match.');
   return false;
  }
 }
}
?>

View

Create a blank document in the views file (application -> views) and name it form_view.php, in the document add all the following code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Captcha in Codeigniter</title>
</head>
<body>
 <?php echo validation_errors('<p>'); ?>
 <?php echo form_open("home/add_message"); ?>
 <p>
  <label for="user_name">Name:</label>
  <input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" />
 </p> 
 <p>
  <label for="con_password">Message:</label>
  <textarea name="message" id="message" value="" cols="50" rows="4"></textarea>
 </p> 
 <p>
  <?php echo $cap_img ?>
  <input type="text" id="captcha" name="captcha" value="" />
 </p> 
 <p>
  <input type="submit" value="Submit" />
 </p>
 <?php echo form_close(); ?>
</body>
</html>

Model

Create a blank document in the models file (application -> models) and name it home_model.php, in the document add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 public function add_message()
 {
  $data=array(
     'username'=>$this->input->post('user_name'),
     'message'=>$this->input->post('message'),
     );
  $this->db->insert('message',$data);
 }
}
?>

Now you have done a from with captcha. All above code is easy to follow and understand, isn't it? But if you have some trouble, don't hesitate to asked me.

13 comments:

  1. hi how torun the captcha in codeigniter i tried to run buy the image are error

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Sir there is an error , image not coming in view page

    ReplyDelete
  4. Undefined variable: cap_img
    what is cap_img??
    image not coming in view page

    ReplyDelete
  5. You should also add unsetting functionality to your codeigniter based captcha. You can do this by adding Unset Captcha code to your refresh captcha function.

    Source: https://www.cloudways.com/blog/captcha-in-codeigniter/

    ReplyDelete
  6. Thanks for sharing the information. It is very useful for my future. keep sharing.

    Best Linux training in Noida
    Linux Training Institute in Noida

    ReplyDelete
  7. Superb blog I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and justifiable. The substance of data is exceptionally instructive.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training

    ReplyDelete
  8. I have been searching for a useful post like this on salesforce course details, it is highly helpful for me and I have a great experience with this Salesforce Training who are providing certification and job assistance. Salesforce institute training in Gurgaon

    ReplyDelete