How to Implement Captcha in CodeIgniter using Captcha Helper

A CAPTCHA (Complete Automated Public Turning test to tell Computer and Human Apart) is a type of challenge test to identify whether the user is human or not. Captcha mostly used in the web application to protect the website from getting spammed. A captcha is very important in the web form where any input is given by the user or any action is processed based on the user’s response.

CAPTCHA is randomly generated string incorporated in an image file which is display to the user and the random string is stored in SESSION variable. Once the user submits the captcha word by viewing captcha image, the submitted value will be compared with the session value. If both the captcha code is matched, further action should take.

In this tutorial, we will show you how to implement CAPTCHA in CodeIgniter. CodeIgniter provides a CAPTCHA helper to generate random code and create CAPTCHA image. CodeIgniter CAPTCHA Helper contains functions that help to generate CAPTCHA images with various customization options.

Here we’ll provide the example code to implement CAPTCHA functionality in CodeIgniter. The following functionality will be implemented in this simple PHP captcha script for CodeIgniter.

  • Create and display captcha image.
  • Get user input and submit for comparison.
  • Compare user input code with captcha word and return the status.

Create CAPTCHA Image in CodeIgniter

To create captcha image, you need to specify the config options and pass this array in create_captcha() function of CAPTCHA helper.

// Captcha configuration
$config = array(
    
'img_path'      => 'captcha_images/',
    
'img_url'       => base_url().'captcha_images/',
    
'img_width'     => '150',
    
'img_height'    => 50,
    
'word_length'   => 8,
    
'font_size'     => 16
);
$captcha create_captcha($config);

Implement CAPTCHA Functionality in CodeIgniter

Now we will show how you can use this captcha code and implement captcha functionality in your CodeIgniter 3 application.

Controller (Captcha.php)

The Captcha controller contains 3 functions, __construct(), index(), and refresh().

__construct()

  • Load the CodeIgniter CAPTCHA helper to generate captcha code and image.
  • Load the Session library to store captcha code for comparison.

index()

  • Generate random word and create captcha image using create_captcha() function.
  • Store captcha code in a SESSION variable.
  • Pass captcha image to view and load the view.
  • Handles the captcha code submission and comparison process.

refresh()
Generate random word, create and display captcha image. Basically, this function is called when the user request for a new captcha.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class 
Captcha extends CI_Controller
{
    function 
__construct() {
        
parent::__construct();
        
        
// Load session library
        
$this->load->library('session');
        
        
// Load the captcha helper
        
$this->load->helper('captcha');
    }
    
    public function 
index(){
        
// If captcha form is submitted
        
if($this->input->post('submit')){
            
$inputCaptcha $this->input->post('captcha');
            
$sessCaptcha $this->session->userdata('captchaCode');
            if(
$inputCaptcha === $sessCaptcha){
                echo 
'Captcha code matched.';
            }else{
                echo 
'Captcha code does not match, please try again.';
            }
        }
        
        
// Captcha configuration
        
$config = array(
            
'img_path'      => 'captcha_images/',
            
'img_url'       => base_url().'captcha_images/',
            
'font_path'     => 'system/fonts/texb.ttf',
            
'img_width'     => '160',
            
'img_height'    => 50,
            
'word_length'   => 8,
            
'font_size'     => 18
        
);
        
$captcha create_captcha($config);
        
        
// Unset previous captcha and set new captcha word
        
$this->session->unset_userdata('captchaCode');
        
$this->session->set_userdata('captchaCode'$captcha['word']);
        
        
// Pass captcha image to view
        
$data['captchaImg'] = $captcha['image'];
        
        
// Load the view
        
$this->load->view('captcha/index'$data);
    }
    
    public function 
refresh(){
        
// Captcha configuration
        
$config = array(
            
'img_path'      => 'captcha_images/',
            
'img_url'       => base_url().'captcha_images/',
            
'font_path'     => 'system/fonts/texb.ttf',
            
'img_width'     => '160',
            
'img_height'    => 50,
            
'word_length'   => 8,
            
'font_size'     => 18
        
);
        
$captcha create_captcha($config);
        
        
// Unset previous captcha and set new captcha word
        
$this->session->unset_userdata('captchaCode');
        
$this->session->set_userdata('captchaCode',$captcha['word']);
        
        
// Display captcha image
        
echo $captcha['image'];
    }
}

View (captcha/index.php)

Initially, the captcha image is shown with an input field and submit button. Once the user submits the captcha word it will be sent to the index() method of Captcha controller for comparison.

<h4>Submit Captcha Code</h4>
<p id="captImg"><?php echo $captchaImg?></p>
<p>Can't read the image? click <a href="javascript:void(0);" class="refreshCaptcha">here</a> to refresh.</p>
<form method="post">
    Enter the code : 
    <input type="text" name="captcha" value=""/>
    <input type="submit" name="submit" value="SUBMIT"/>
</form>

Also, the user can request a new captcha image by refresh link. The jQuery and Ajax code will execute by clicking the refresh link. The new captcha image will be fetched from the refresh() method of Captcha controller and the existing captcha image will be replaced with a new image.

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- captcha refresh code -->
<script>
$(document).ready(function(){
    $('.refreshCaptcha').on('click', function(){
        $.get('<?php echo base_url().'captcha/refresh'; ?>', function(data){
            $('#captImg').html(data);
        });
    });
});
</script>

CAPTCHA Configuration Options

Various configuration options are available in create_captcha() function to customize the captcha image. Some useful configuration options are given below:

  • img_path – Required. The path where the captcha images will be stored.
  • img_url – Required. The URL of the captcha image.
  • img_width – Optional. The width of the captcha image. Defaults to 150.
  • img_height – Optional. The height of the captcha image. Defaults to 30.
  • word_length – Optional. The number of characters. Defaults to 8.
  • font_size – Optional. The font size of the captcha word. Defaults to 16.
  • font_path – Optional. The path of text font. Specify the font path, if you want to use different text font for captcha word.
  • pool – Optional. Defaults to '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. Specify the letters which you want to use in the captcha code.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

9 Comments

  1. Karthikeyan Murugan Said...
  2. Siddharth Said...
    • CodexWorld Said...
  3. Krishna Kanth Said...
  4. Muhammad Umar Bilal Said...
  5. Sreejith Said...
  6. Johan Van De Merwe Said...
  7. Rajkamal Said...
    • CodexWorld Said...

Leave a reply

keyboard_double_arrow_up