CodeIgniter Captcha

CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") is a type of challenge–response test used in computing to determine whether the user is human or not. CAPTCHA mostly used in the web application to protect the website from getting spammed. In a CAPTCHA Verification, the respondent is presented with a picture (or "challenge") of words or characters, and the respondent must correctly type out those characters in order to proceed.

The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images.

In this tutorial, we'll see how to implement CAPTCHA in CodeIgniter.

Loading CAPTCHA Helper

$this->load->helper('captcha);

Adding a Database

we'll need to add the information returned from create_captcha() to your database. Below the table prototype:

CREATE TABLE captcha (
        captcha_id bigint(13) unsigned NOT NULL auto_increment,
        captcha_time int(10) unsigned NOT NULL,
        ip_address varchar(45) NOT NULL,
        word varchar(20) NOT NULL,
        PRIMARY KEY `captcha_id` (`captcha_id`),
        KEY `word` (`word`)
);

Using a text editor, create a controller called Mycaptcha.php. In it, place this code and save it to your application/controllers/ directory:

<?php
  
   class Mycaptcha extends CI_Controller {
   
      public function __construct() { 
         parent::__construct(); 
         $this->load->helper(array('form', 'url', 'captcha', 'html')); 
      } 
	
      public function index() {
			
         /* Load form validation library */ 
         $this->load->library('form_validation');
			
	 /* Validation rule */
	 $this->form_validation->set_rules('captcha', 'Captcha', 'required|callback_checkCaptcha');	 
			
         if ($this->form_validation->run() == FALSE) {
		        $arr = array(
			            'img_path'    => './captcha/',
				    'img_url'     => base_url().'/captcha/',
				    'word_length' => 4
				 );
			 $captcha = create_captcha($arr);
			 $data = array(
					'captcha_time'  => $captcha['time'],
					'ip_address'    => $this->input->ip_address(),
					'word'          => $captcha['word']
				      );
		
			$query = $this->db->insert_string('captcha', $data);
			$this->db->query($query);

			$this->load->view('captcha_form', compact('captcha')); 
         } 
         else {
		    $success = "Captcha has been successfully verified!";
                    $this->load->view('captcha_form', compact('success')); 
         } 
      }

	public function checkCaptcha($captcha)
	   {
		   // First, delete old captchas
		   $expiration = time() - 7200; // Two hour limit
		   $this->db->where('captcha_time < ', $expiration)->delete('captcha');
		   // Then see if a captcha exists:
		   $sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?';
		   $binds = array($captcha, $this->input->ip_address(), $expiration);
		   $query = $this->db->query($sql, $binds);
		   $row = $query->row();
		   if ($row->count ==  0) {
			  $this->form_validation->set_message('checkCaptcha','The code you entered is incorrect');
			  return FALSE;
			}
		  else 
			  return TRUE;
		}
	}
?>

Note: create a captcha directory under root folder.

Using a text editor, create a form called captcha_form.php. In it, place this code and save it to your application/views/ directory:

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <div class="col-md-2"></div>
     <div class="col-md-8" style="margin-top:20px">
	    <?php
		   echo form_open('mycaptcha/index');
		   echo validation_errors();
		   if (isset($success)) {
		     echo '<p>'.$success.'</p>';
		  } else {
	    ?>
		<div class="form-group">
			<label for="image">Image:</label>
			<?php echo img('captcha/'.$captcha['filename']); ?>
		</div>
		<div class="form-group">
			<label for="captcha">Type the code shown:</label>
			<input type="text" id="captcha" name="captcha" />
		</div>
		<button type="submit" class="btn btn-success">Submit</button>
		<?php 
		echo form_close(); 
	     }
		?>
		</div>
	 <div class="col-md-2"></div>
	</body>
</html>

To try captcha form, visit your site using a URL similar to this one:

http://localhost/codeigniter/index.php/mycaptcha/index

codeigniter captcha codeigniter captcha2 codeigniter captcha3