Captcha Plugin in CodeIgniter

CAPTCHACompletely Automated Public Turing test to tell Computers and Humans Apart. It is used in webpages to protect your page from automatic posting from outside of the site. CodeIgniter framework has a plugin named “captcha_pi.php” in plugins folder. Here I’ve demonstrated an example how to use this captcha plugin in your website built in CodeIgniter framework.

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

<?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 CodeIgniter captcha plugin and returns the array. Captcha word is saved in session and after submitting the form this session word is compared with the posted word for matching.

If matches which is in (strcasecmp($_SESSION['captchaWord'], $_POST['confirmCaptcha']) == 0), then success is shown. Otherwise failure is shown. Here I’ve used strcasecmp() function of php to compare the word as case-insensitively. If u 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 strcmp() function.

The captcha_model.php is as follows:

<?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’ve created a folder “tmp” and sub-folder “captcha” in the main directory where index.php exists. If u run on server be sure this two folder are given write permission.

By default, Captcha plugin generates 8 words in length. But I desire to very this length. So, I’ve made a little change in this plugin. In line 156 of "captcha_pi.php" there was

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

which I made

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

Next, in line 226, there was

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

which I made

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

Now if u pass word_length as parameter then it will generate captcha image of word length as you specify.

Captcha

You can download the whole package from here.

captchademo

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Tags: , , , ,

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

24 Responses to “Captcha Plugin in CodeIgniter”


  1. I recently came accross your blog and have been reading along. I thought I would leave my first comment. I dont know what to say except that I have enjoyed reading. Nice blog.

    Tim Ramsey


  2. Thank you for your comment. :)


  3. Nice n helpful post. But I couldn’t but feel amused at the irony in the first comment – the first comment is actually a spam (search up the exact text on google including the misspelled accross and you will find it on tons of blogs). Time to get yourself a captcha control on the comments :)


  4. @ Dhananjay Nene
    Thanks for your suggestion. Soon, I will include captcha in my blog. :)


  5. Nice post. How about a post on integrating re-CAPTCHA service on Code Igniter ? :)


  6. Nice One…
    But 1 question:
    How can I change the background color/image for this captcha?


  7. It’s actually the ‘turing test’ after Alan Turing not ‘turning’ otherwise interesting thanks


  8. @Struth Thanks. I have made correction.


  9. Great post, I will have a look at putting this onto one of my future CI projects.

    @Anuj, you just need to check the captcha_pi plugin and change the variables for assigning colors to suit.


  10. May 2008…?!?

    I try to find this tutorial today…. hahahahaha

    thank’s alot… it’s really helpfull


  11. thank’s alot… it’s really helpfull

  12. pradeepa Says:

    it is very helpfull but image is not displaying for me
    please anyone help me out


  13. thank you very much. nice blog there.

  14. girlicious143 Says:

    thank you so much. this is very helpfull


  15. This is just what I was looking for. Thanks.


  16. superb..

    exactly what I was looking for. Bookmarked it. nice blog :)


  17. [...] I found two articles which help me out how to install it. http://d.hatena.ne.jp/dix3/20080925 and http://www.blog.valenticabd.com/2008/05/23/captcha-plugin-in-codeigniter.html The first one is in Japanese. But don’t be disappointed with it. You can find the controll [...]


  18. I have tried to use this one but when I post the captcha value into the form value then the session value and post value doesn’t match never I am not sure why this is occurring. Can you suggest me why this is happening.


  19. @Shahriat After posting the form echo your posted value of captcha and session value of captcha. May be wrong input field was being compared. Thanks

  20. Michael Connors Says:

    Thank you for your tutorial. I have followed your steps but I still cannot get the image to display. I keep getting this error
    A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: captcha

    Filename: views/listings_showlisting_view.php

    Line Number: 238

    Any suggestions?


  21. @Michael: Probably you have not assigned ‘captcha’ variable in the controller or have not passed as parameter when you are loading view. Download my code snippets and try accordingly. Thanks.

  22. Michael Connors Says:

    I am sorry to be a nuisance but I have been beating my head against the captcha wall all week.

    My company hosts several sites and I am trying to implement this one just one of them. If the URL for the site (for example) is http://www.google.com would that be both my $baseUrl and $basePath?

    Thank you for your help so far.

  23. Michael Connors Says:

    I am sorry to be a nuisance but I have been beating my head against the captcha wall all week.

    My company hosts several sites and I am trying to implement this one just one of them. If the URL for the site (for example) is http://www.google.com would that be both my $baseUrl and $basePath?

    Thank you for your help so far!


  24. @Michael, the $baseUrl is the url (i.e. the domain address), but $basePath is not the url. Rather it is the hard drive path, such as: in Windows it may be ‘D:/apache2triad/htdocs/captchademo/’ and Linux server it may be ‘/www/var/htdocs/’ depending on your server configuration. Remember $basePath is used to display the image where the captcha image is generated. So, you must assign the relative location of the project to $basePath (again not the url). Hope this will help.

Leave a Reply