Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Captcha Plug-in in CodeIgniter

4.92/5 (12 votes)
29 Jul 2008CPOL2 min read 1   2.3K  
How to use thr captcha plugin in CodeIgniter.

Introduction

CAPTCHA - Completely Automated Public Turning test to tell Computers and Humans Apart. It is used in web pages to protect your page from automatic posting from outside of the site. The CodeIgniter framework has a plugin named "captcha_pi.php" in the plugins folder. Here I've demonstrated an example of how to use this captcha plug-in in your website's built-in CodeIgniter framework.

Let's Start

Make a controller named "captcha.php" and place it in the "controllers" folder. This controller is as follows:

PHP
<?php
class Captcha extends Controller
{
  public function __construct()
  {
    parent::Controller();

    $this->load->model('captcha_model');

    session_start();
  }

  public function index()
  {
    if(empty($_POST))
    {
      $captcha = $this->captcha_model->generateCaptcha();

      $_SESSION['captchaWord'] = $captcha['word'];

      $data['captcha'] = $captcha;

      $this->load->view('show_view', $data);
    }
    else
    {
      //check captcha matches
      if(strcasecmp($_SESSION['captchaWord'],
                    $_POST['confirmCaptcha']) == 0)
      {
        $this->load->view('success_view');
      }
      else
      {
        $this->load->view('failure_view');
      }
    }
  }
}
?>

Here, I've made a model named "captcha_model" that has a method generateCaptcha(), which generates the captcha using the CodeIgniter captcha plug-in and returns an array. The captcha word is saved in the session, and after submitting the form, this session word is compared with the posted word for matching.

If it matches, which is in the condition (strcasecmp($_SESSION['captchaWord'], $_POST['confirmCaptcha']) == 0), then success is shown. Otherwise, failure is shown. Here, I've used the strcasecmp() function of PHP to compare the word case-insensitively. If you want user to enter the captcha words as they are shown (i.e., capital letter in capital and small letter in small), then you can use the strcmp() function.

The captcha_model.php is as follows:

PHP
<?php
class Captcha_model extends Model
{
  private $vals = array();

  private $baseUrl  = 'http://localhost/captchademo/';
  private $basePath = 'D:/apache2triad/htdocs/captchademo/';

  private $captchaImagePath = 'tmp/captcha/';
  private $captchaImageUrl  = 'tmp/captcha/';
  private $captchaFontPath  = 'c:/windows/fonts/verdana.ttf';

  public function __construct($configVal = array())
  {
    parent::Model();

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

    if(!empty($config))
      $this->initialize($configVal);
    else
      $this->vals = array(
                 'word'          => '',
                 'word_length'   => 6,
                 'img_path'      => $this->basePath
                                 .  $this->captchaImagePath,
                 'img_url'       => $this->baseUrl
                                 .  $this->captchaImageUrl,
                 'font_path'     => $this->captchaFontPath,
                 'img_width'     => '150',
                 'img_height'    => 50,
                 'expiration'    => 3600
               );
  }

  /**
   * initializes the variables
   *
   * @author    Mohammad Jahedur Rahman
   * @access    public
   * @param     array     config
   */
  public function initialize ($configVal = array())
  {
    $this->vals = $configVal;
  } //end function initialize

  //---------------------------------------------------------------

  /**
   * generate the captcha
   *
   * @author     Mohammad Jahedur Rahman
   * @access     public
   * @return     array
   */
  public function generateCaptcha ()
  {
    $cap = create_captcha($this->vals);

    return $cap;
  } //end function generateCaptcha
}
?> 

You have to change the $baseUrl, $basePath, $captchaImagePath, $captchaImageUrl, and $captchaFontPath etc. To store the captcha images, at first, I created a folder "tmp" and a sub-folder "captcha" in the main directory where index.php exists. If you are running the code on the server, be sure these two folders are given write permission.

By default, the captcha plug-in generates 8 letter words. But, I wanted to vary this length. So, I made a little change in this plug-in. In line 156 of "captcha_pi.php":

PHP
$defaults = array('word'       => '',    'img_path' => '',
                  'img_url'    => '',    'img_width' => '150',
                  'img_height' => '30',  'font_path' => '',
                  'expiration' => 7200);  

was changed to:

PHP
$defaults = array('word'      => '',    'word_length' => 8,
                  'img_path'  => '',    'img_url'     => '',
                  'img_width' => '150', 'img_height'  => '30',
                  'font_path' => '',    'expiration'  => 7200);

Next, line 226:

PHP
for ($i = 0; $i < 8; $i++)

was changed to:

PHP
for ($i = 0; $i < $word_length; $i++)

Now, if you pass word length as a parameter, then it will generate a captcha image of the word length you have specified.

captchademo

Points of Interest

Although it is easier to use the captcha plug-in in CodeIgniter, I suggest you use ReCaptcha.

You can read my blog here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)