Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Implement CAPTCHA in CodeIgniter

December 19, 2017

3 Min Read
Reading Time: 3 minutes

In this tutorial, I will demonstrate how you can easily implement CAPTCHA in your CodeIgniter projects built on any hosting for PHP.

CAPTCHA in CodeIgniter

CAPTCHA is a randomly generated string (or a set of images) that appears when verification is required. It is an essential requirement for cutting down the spam at a website. In many cases, it is the only line of defense a website has against bots that spam websites.

Create Controller

The process starts with the creation of the Controller.

Create a file named captcha.php in the Controller folder. Open the file in your code editor and add the following code to it:

<?php
defined('BASEPATH') OR exit('your exit message');
class Captcha extends CI_Controller
{function __construct(){
    parent::__construct();
    $this->load->library('session');
    $this->load->helper('captcha');
}
    public function index(){
        if ($this->input->post('submit')) {
            $captcha_insert = $this->input->post('captcha');
            $contain_sess_captcha = $this->session->userdata('valuecaptchaCode');
            if ($captcha_insert === $contain_sess_captcha) {
                echo 'Success';
            } else {
                echo 'Failure';
            }
        }
        $config = array(
            'img_url' => base_url() . 'image_for_captcha/',
            'img_path' => 'image_for_captcha/',
            'img_height' => 45,
            'word_length' => 5,
            'img_width' => '45',
            'font_size' => 10
        );
        $captcha = create_captcha($config);
        $this->session->unset_userdata('valuecaptchaCode');
        $this->session->set_userdata('valuecaptchaCode', $captcha['word']);
        $data['captchaImg'] = $captcha['image'];
        $this->load->view('captcha/index', $data);
    }
    public function refresh()
    {
        $config = array(
            'img_url' => base_url() . 'image_for_captcha/',
            'img_path' => 'image_for_captcha/',
            'img_height' => 45,
            'word_length' => 5,
            'img_width' => '45',
            'font_size' => 10
        );
        $captcha = create_captcha($config);
        $this->session->unset_userdata('valuecaptchaCode');
        $this->session->set_userdata('valuecaptchaCode', $captcha['word']);
        echo $captcha['image'];
    }
}

 

Code Explanation

Here is a brief explanation of the various components of the Controller code:

Load CAPTCHA Helper  

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

Form Submission

if ($this->input->post('submit')) {

           $captcha_insert = $this->input->post('captcha');

           $contain_sess_captcha = $this->session->userdata('valuecaptchaCode');

           if ($captcha_insert === $contain_sess_captcha) {

               echo 'Success';

           } else {

               echo 'Failure';

           }

       }

CAPTCHA Configuration

'img_url' => base_url() . 'image_for_captcha/',

           'img_path' => 'image_for_captcha/',

           'img_height' => 45,

           'word_length' => 5,

           'img_width' => '45',

           'font_size' => 10

Refresh CAPTCHA

public function refresh()

   {

       $config = array(

           'img_url' => base_url() . 'image_for_captcha/',

           'img_path' => 'image_for_captcha/',

           'img_height' => 45,

           'word_length' => 5,

           'img_width' => '45',

           'font_size' => 10

       );

       $captcha = create_captcha($config);

       $this->session->unset_userdata('valuecaptchaCode');

       $this->session->set_userdata('valuecaptchaCode', $captcha['word']);

       echo $captcha['image'];

   }

Unset Previous CAPTCHA and Set a New One

$this->session->unset_userdata('valuecaptchaCode');

$this->session->set_userdata('valuecaptchaCode', $captcha['word']);

Load the View

   $this->load->view('captcha/index', $data);

You might also like: How To Host CodeIgniter PHP On Cloud

Create the View

The next step is the creation of the View. for this, create a folder in the View folder. Go into the folder and create another folder with the name captcha. inside this folder, create a file named index.php. Add the following code to the file:

<!DOCTYPE html>

<html>

<head>

   <title>Implement Captcha in Codeigniter using helper</title>

   <script>

       $(document).ready(function(){

           $('.captcha-refresh').on('click', function(){

               $.get('<?php echo base_url().'captcha/refresh'; ?>', function(data){

                   $('#image_captcha').html(data);

               });

           });

       });

   </script>

   <script src="<?php echo base_url(); ?>/js/jquery.js"></script>

</head>

<body>

<p id="image_captcha"><?php echo $captchaImg; ?></p>

<a href="javascript:void(0);" class="captcha-refresh" ><img src="<?php echo base_url().'images/refresh.png'; ?>"/></a>

<form method="post">

   <input type="text" name="captcha" value=""/>

   <input type="submit" name="submit" value="SUBMIT"/>

</form>

</body>

</html>



You Might Also Like: Learn to Implement CodeIgniter Form Validation 

Another Method of Calling CAPTCHA in CodeIgniter with Validation

Here is another method that is used to call in CAPTCHA through CodeIgniter helper and then validate it.

<?php

class Captcha extends CI_Controller

{

   public function index()

   {

       $this->load->helper(array('form', 'url', 'captcha'));

       $this->load->library('form_validation');

       $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

       $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');

       $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

       $this->form_validation->set_rules('captcha', 'Captcha', 'callback_validate_captcha');

       if ($this->form_validation->run() == FALSE) {

           $original_string = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));

           $original_string = implode("", $original_string);

           $captcha = substr(str_shuffle($original_string), 0, 6);



           $vals = array(

               'word' => $captcha,

               'img_path' => 'image_for_captcha/',

               'font_size' => 10,

               'img_width' => 150,

               'img_height' => 50,

               'expiration' => 7200

           );

           $cap = create_captcha($vals);

           $data['image'] = $cap['image'];

           if (file_exists(BASEPATH . "../captcha/" . $this->session->userdata['image']))

               unlink(BASEPATH . "../captcha/" . $this->session->userdata['image']);

           $this->session->set_userdata(array('captcha' => $captcha, 'image' => $cap['time'] . '.jpg'));

           $this->load->view('index_index', $data);

       } else {

           if (file_exists(BASEPATH . "../captcha/" . $this->session->userdata['image']))

               unlink(BASEPATH . "../captcha/" . $this->session->userdata['image']);

           $this->session->unset_userdata('captcha');

           $this->session->unset_userdata('image');

           redirect('home', 'refresh');

       }

   }



   public function validate_captcha()

   {

       if ($this->input->post('captcha') != $this->session->userdata['captcha']) {

           $this->form_validation->set_message('validate_captcha', 'Cpatcha Code is wrong');

           return false;

       } else {

           return true;

       }

   }

}

You might also like: How To Pass Data From Controller To View In CodeIgniter

Conclusion

In this tutorial, I discussed how you could easily integrate CAPTCHA into CodeIgniter projects. If you need help. just drop a comment and I will get back to you.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Owais Alam

is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at owais.alam@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!