This tutorial will show you how to generate captcha image using Codeigniter Captcha Helper. The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images.

The CAPTCHA helper

The captcha function requires the GD image library.
Only the img_path and img_url are required.
If a word is not supplied, the function will generate a random ASCII string. You might put together your own word library that you can draw randomly from.
If you do not specify a path to a TRUE TYPE font, the native ugly GD font will be used.
The “captcha” directory must be writable
The expiration (in seconds) signifies how long an image will remain in the captcha folder before it will be deleted. The default is two hours.
word_length defaults to 8, pool defaults to ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’
font_size defaults to 16, the native GD font has a size limit. Specify a “true type” font for bigger sizes.
The img_id will be set as the “id” of the captcha image.
If any of the colors values is missing, it will be replaced by the default.



Netbeans 8.1
XAMPP in Windows
Codeigniter 3.0.6

Configure XAMPP and Netbeans

From Netbeans IDE go to Tools->Options. Click on PHP. Now on tab “General” browse the file for “PHP 5 Interpreter”. The php interpreter file generally placed inside the <physical drive in Windows OS>:xamppphpphp.exe

Configure Codeigniter and Netbeans

Create a new PHP project in Netbeans. Then remove the index.php file from the newly created project. Now copy the extracted files from Codeigniter 3.0.6 to the newly created project directory.

Directory Structure

A typical directory structure for the project would be as shown below. Here the captcha directory will contain the created captcha image file.
codeigniter captcha directory

Read also Adding Captcha to Database using Codeigniter

Step 1. Now modify <root directory>/application/config/autoload.php file for auto-loading html, url, file, form and session

$autoload['helper'] = array('html', 'url', 'file', 'form');

$autoload['libraries'] = array('session');

Step 2. Now modify <root directory>/application/config/config.php file to define some captcha config

$config['encryption_key'] = '2d8+e6]K0?ocWp7&`K)>6Ky"|.x|%nuwafC~S/+6_mZI9/17y=sKKG.;Tt}k';

  | Captcha
  | 'captcha_form' = Whether captcha will be used in a form or not
  | 'captcha_path' = Directory where the catpcha will be created.
  | 'captcha_fonts_path' = Font in this directory will be used when creating captcha.
  | 'captcha_font_size' = Font size when writing text to captcha. Leave blank for random font size.
  | 'captcha_grid' = Show grid in created captcha.
  | 'captcha_expire' = Life time of created captcha before expired, default is 3 minutes (180 seconds).
  | 'captcha_case_sensitive' = Captcha case sensitive or not.
$config['captcha_form'] = TRUE;
$config['captcha_path'] = 'captcha/';
$config['captcha_fonts_path'] = 'captcha/fonts/1.ttf';
$config['captcha_width'] = 200;
$config['captcha_height'] = 50;
$config['captcha_font_size'] = 14;
$config['captcha_grid'] = FALSE;
$config['captcha_case_sensitive'] = TRUE;

Step 3. Create a view file under <root directory>/application/views which will be used as a registeration form with captcha

<!DOCTYPE html>
        <meta charset="UTF-8">
        <title>Codeigniter Captcha Example</title>
        <style type="text/css">

            ::selection { background-color: #E13300; color: white; }
            ::-moz-selection { background-color: #E13300; color: white; }

            body {
                background-color: #fff;
                margin: 40px;
                font: 13px/20px normal Helvetica, Arial, sans-serif;
                color: #4F5155;

            #body {
                margin: 0 15px 0 15px;

            #container {
                margin: 10px;
                border: 1px solid #D0D0D0;
                box-shadow: 0 0 8px #D0D0D0;

            .error {
                color: #E13300;

            .success {
                color: darkgreen;
        <div id="container">
            <h1>CodeIgniter Captcha Example</h1>

            <div id="body">                
                if (isset($success) && strlen($success)) {
                    echo '<div class="success">';
                    echo '<p>' . $success . '</p>';
                    echo '</div>';
                if (validation_errors()) {
                    echo validation_errors('<div class="error">', '</div>');
                $attributes = array('name' => 'captcha_form', 'id' => 'captcha_form');
                echo form_open($this->uri->uri_string(), $attributes);
                <p>Email Address : <input name="email" id="email" type="text" /></p>
                <p>Password : <input name="pwd" id="pwd" type="password" /></p>
                <p>Confirm Password : <input name="cnf_pwd" id="cnf_pwd" type="password" /></p>
                if ($captcha_form) {
                    <p>Captcha : <input name="not_robot" id="not_robot" type="text" /></p>
                    <p><?php echo $captcha_html; ?></p>
                <p><input name="register" value="Register" type="submit" /></p>
                echo form_close();


Step 4. Create a Controller class under <root directory>/application/controllers for handling client’s request and response


defined('BASEPATH') OR exit('No direct script access allowed');

 * Description of Captcha
 * @author
class Captcha_Form extends CI_Controller {

    function __construct() {

    public function index() {
        $captcha_form = $this->config->item('captcha_form');
        $data['captcha_form'] = $captcha_form;
        if ($captcha_form) {
            $data['captcha_html'] = $this->session->flashdata('captcha_image') != NULL ? $this->session->flashdata('captcha_image') : $this->_create_captcha();
        if ($this->input->post('register')) {
            $this->form_validation->set_rules('pwd', 'Password', 'required');
            $this->form_validation->set_rules('cnf_pwd', 'Password Confirmation', 'required|matches[pwd]');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
            if ($captcha_form) {
                $this->form_validation->set_rules('not_robot', 'Captcha', 'required|callback__check_captcha');
            if ($this->form_validation->run()) {
                $data['captcha_html'] = $this->_create_captcha();
                $data['success'] = 'You have successfully registered';
        $this->load->view('captcha', $data);

     * Create CAPTCHA image to verify user as a human
     * @return    string
    function _create_captcha() {
        $cap_config = array(
            'img_path' => './' . $this->config->item('captcha_path'),
            'img_url' => base_url() . $this->config->item('captcha_path'),
            'font_path' => './' . $this->config->item('captcha_fonts_path'),
            'font_size' => $this->config->item('captcha_font_size'),
            'img_width' => $this->config->item('captcha_width'),
            'img_height' => $this->config->item('captcha_height'),
            'show_grid' => $this->config->item('captcha_grid'),
            'expiration' => $this->config->item('captcha_expire'),
            'ip_address' => $this->input->ip_address(),
            // White background and border, black text and red grid
            'colors' => array(
                'background' => array(255, 255, 255),
                'border' => array(255, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
        $cap = create_captcha($cap_config);
        // Save captcha params in session
            'captcha_word' => $cap['word'],
            'captcha_image' => $cap['image']
        return $cap['image'];

     * Callback function. Check if CAPTCHA test is passed.
     * @param    string
     * @return    bool
    function _check_captcha($code) {
        $word = $this->session->flashdata('captcha_word');
        if (($this->config->item('captcha_case_sensitive') AND $code != $word) OR
                strtolower($code) != strtolower($word)) {
            $this->form_validation->set_message('_check_captcha', 'Captcha is incorrect');
            return FALSE;
        return TRUE;


Step 5. Now modify <root directory>/application/config/routes.php file for pointing the default controller class

$route['default_controller'] = 'captcha_form';

Step 6. Now if everything is fine run the application, you will see below output in the browser

codeigniter captcha

Step 7. Now if you do not put anything and submit the form then error messages displayed

codeigniter captcha

Step 8. If both passwords do not match then you see the below error message

codeigniter captcha

Step 9. If you enter incorrect captcha then you will see below error message

codeigniter captcha

Step 10. If everything is entered correctly then you will see below success message
codeigniter captcha

Thanks for reading.


Leave a Reply

Your email address will not be published. Required fields are marked *