Posted by Arjun on Wednesday 15th January 2014

How to use Captcha in CodeIgniter?

Captcha CodeIgniter CodeIgniter beginners How to CodeIgniter 3

In this tutorial, I will show you integrating Captcha in your CodeIgniter application. We gonna use CI's builtin captcha helper and contains functions that assist in creating CAPTCHA images. This helper needs GD library installed on your server.

How to use Captcha in CodeIgniter

Here are the steps to use Captcha helper in the CodeIgniter 3 application forms:

Download and Install

Step 1: Download from the official website and install CodeIgniter.

Create Controller

Step 2: Lets create a contoller called captcha.php with below code in application/controllers/captcha.php.

<?php if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Captcha extends CI_Controller
{
    /* Initialize the controller by calling the necessary helpers and libraries */
    public function __construct()
    {
        parent::__construct();
        /* Load the libraries and helpers */
        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->helper(array('form', 'url', 'captcha'));
    }

    /* The default function that gets called when visiting the page */
    public function index()
    {
        /* Set form validation rules */
        $this->form_validation->set_rules('name', "Name", 'required');
        $this->form_validation->set_rules('captcha', "Captcha", 'required');

        /* Get the user's entered captcha value from the form */
        $userCaptcha = $this->input->post('captcha');

        /* Check if form (and captcha) passed validation*/
        if ($this->form_validation->run() == true && strcmp(strtolower($userCaptcha), strtolower($this->session->userdata('captchaWord'))) == 0) {
            /** Validation was successful; show the Success view **/
            /* Clear the session variable */
            $this->session->unset_userdata('captchaWord');
            /* Get the user's name from the form */
            $name = $this->input->post('name');
            /* Pass in the user input to the success view for display */
            $data = array('name' => $name);
            // do as your requirement
            print_r($data);exit;
        } else {
            /** Validation was not successful - Generate a captcha **/
            /* Setup vals to pass into the create_captcha function */
            $captcha = $this->_generateCaptcha();
            
            /* Store the captcha value (or 'word') in a session to retrieve later */
            $this->session->set_userdata('captchaWord', $captcha['word']);
         
            /* Load the captcha view containing the form (located under the 'views' folder) */
            $this->load->view('captcha_view', $captcha);
        }
    }

    // this function will create captcha
    private function _generateCaptcha()
    {
        $vals = array(
            'img_path' => './captcha_images/',
            'img_url' => base_url('captcha_images/'),
            'img_width' => '150',
            'img_height' => 30,
            'expiration' => 7200,
        );
        /* Generate the captcha */
        return create_captcha($vals);
    }
}
/* End of file captcha.php */
/* Location: ./application/controllers/captcha.php */

The _generateCaptcha() method will generate captcha image and will place generated image inside captcha_images directory as configurated and you must create captcha_images directory in your codeigniter project root directory and change its permission to 777 or 666.

Create a form

Step 2: Crate a View file called captcha_view.php in the applications/views/captcha_view.php

<?php echo validation_errors(); ?> 
<?php echo form_open('captcha'); ?>
<p>
  <label for="name">Name:
    <input id="name" name="name" type="text" />
  </label>
</p>
<?php echo $image; ?>
<p>
  <label for="name">Captcha:
    <input id="captcha" name="captcha" type="text" />
  </label>
</p>
<?php echo form_submit("submit", "Submit"); ?> 
<?php echo form_close(); ?>