This tutorial will show you how to generate captcha image using Codeigniter Captcha Helper and store captcha characters into database. 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.


Prerequisites

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 and the generated captcha characters will be stored into database.

codeigniter captcha directory

Read also Captcha 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('database', '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_expire'] = 180;
$config['captcha_case_sensitive'] = TRUE;

Step 3. Now modify <root directory>/application/config/database.php file to add database config

$db['default'] = array(
    'dsn' => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'codeigniter',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    ...more
);

Step 4. Now create captcha table in codeigniter database

CREATE TABLE captcha (
        captcha_id bigint(13) unsigned NOT NULL auto_increment,
        captcha_time int(10) unsigned NOT NULL,
        ip_address varchar(45) NOT NULL,
        word varchar(20) NOT NULL,
        PRIMARY KEY `captcha_id` (`captcha_id`),
        KEY `word` (`word`)
);

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

<!DOCTYPE html>
<html>
    <head>
        <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;
            }
        </style>
    </head>
    <body>
        <div id="container">
            <h1>CodeIgniter Captcha Example</h1>

            <div id="body">                
                <?php
                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>');
                }
                ?>
                <?php
                $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>
                <?php
                if ($captcha_form) {
                    ?>
                    <p>Captcha : <input name="not_robot" id="not_robot" type="text" /></p>
                    <p><?php echo $captcha_html; ?></p>
                    <?php
                }
                ?>
                <p><input name="register" value="Register" type="submit" /></p>
                <?php
                echo form_close();
                ?>
            </div>

        </div>
    </body>
</html>

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

<?php

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

/**
 * Description of Captcha
 *
 * @author https://www.roytuts.com
 */
class Captcha_Form extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
    }

    function index() {
        $captcha_form = $this->config->item('captcha_form');
        $data['captcha_form'] = $captcha_form;
        if ($captcha_form) {
            $data['captcha_html'] = $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);
    }

    function _create_captcha() {
        $this->load->helper('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'),
            '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 database
        $data = array(
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']
        );
        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);
        return $cap['image'];
    }

    function _check_captcha($code) {
        // First, delete old captchas
        $expiration = time() - $this->config->item('captcha_expire'); // 3 mins limit
        $this->db->where('captcha_time < ', $expiration)
                ->delete('captcha');
        // Then see if a captcha exists:
        $sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?';
        $binds = array($code, $this->input->ip_address(), $expiration);
        $query = $this->db->query($sql, $binds);
        $row = $query->row();
        if ($row->count == 0) {
            $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. At the same time if you look into database table you will see that captcha characters are stored.

codeigniter captcha

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.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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