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 all web application to protect the website from getting spammed. A captcha is very important where any input is given from user or any action is processed based on the user 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 compare with the session value. If both the captcha code is matched, further action should take.

In this tutorial, we’ll demonstrate how to implement captcha in CodeIgniter. CodeIgniter provides a captcha helper to create CAPTCHA. CodeIgniter CAPTCHA Helper helps to generate captcha image with customization options. Here we’ll provide the example code to implement captcha functionality in CodeIgniter. The following functionality will be added to this simple PHP captcha script for CodeIgniter.

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

The following code is used to create captcha in CodeIgniter.

// 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);

You can use a different font for captcha word by specifying font_path value in captcha configuration array.

'font_path'     => './path/to/fonts/texb.ttf'

Now we’ll show how you can use this captcha script in your CodeIgniter application. Before you begin, take a look at the application folders and files structure.

create-captcha-in-codeigniter-folders-files-structure-codexworld

Controller (Captcha.php)

To using the CodeIgniter captcha helper, you need to load captcha helper which is included in __construct() function.
index() function creates captcha, pass the captcha image to view, and load the respective view. Also, handles the captcha submission and comparison process.
refresh() function is used 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 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 was not match, please try again.';
            }
        }
        
        
// 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);
        
        
// Unset previous captcha and store new captcha word
        
$this->session->unset_userdata('captchaCode');
        
$this->session->set_userdata('captchaCode',$captcha['word']);
        
        
// Send 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/',
            
'img_width'     => '150',
            
'img_height'    => 50,
            
'word_length'   => 8,
            
'font_size'     => 16
        
);
        
$captcha create_captcha($config);
        
        
// Unset previous captcha and store 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 view file is loaded with captcha image, refresh image, 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.

Also, the user can request for a new captcha image by refresh link. An ajax script would run on refresh link click, then new captcha image is fetched from the refresh() method of Captcha controller and replace the captcha image with new image.

<!DOCTYPE html>
<html>
<head>
    <title>Captcha implement in CodeIgniter by CodexWorld</title>
    <script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $('.refreshCaptcha').on('click', function(){
            $.get('<?php echo base_url().'captcha/refresh'?>', function(data){
                $('#captImg').html(data);
            });
        });
    });
    </script>
</head>
<body>
    <p>Submit the word you see below:</p>
    <p id="captImg"><?php echo $captchaImg?></p>
    <a href="javascript:void(0);" class="refreshCaptcha" ><img src="<?php echo base_url().'assets/images/refresh.png'?>"/></a>
    <form method="post">
        <input type="text" name="captcha" value=""/>
        <input type="submit" name="submit" value="SUBMIT"/>
    </form>
</body>
</html>

2 Comments

  1. Rajkamal Said...
    • CodexWorld Said...

Leave a reply

Connect With CodexWorld