How to use Codeigniter captcha plug-in Part 1

DOWN LOAD FILES

(updated: 2 November 2009)

I have read a note in Codeigniter captcha_pi.php. You can find this file in system/plugins.
However this does not explain well. This post hopefully explains how to use this plugin. And I will show a bit different way in the next post.

I found the following two articles are very helpful and credits should go to them.

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 code and view code at the end of the blog. These two have English notes as well.

The first step is following what a note in captcha_pi.php is telling.

Environment

I am using XAMPP for my development.
I freshly installed a codeigniter1.7.2 in hdocs and renamed as ci_captcha.
I have not added a .htaccess file nor moving application out of system folder.

Preparation

captcha folder

You need to create a folder called captcha. I created it in the same level as system folder.
ci_captcha/captcha
When you create captcha images, this is the place where all the images are saved.

Database

I used Phpmyadmin to create a database called ci_captcha.
Enter this sql.

CREATE TABLE IF NOT EXISTS `captcha` (
  `captcha_id` bigint(13) unsigned NOT NULL AUTO_INCREMENT,
  `captcha_time` int(10) unsigned NOT NULL,
  `ip_address` varchar(16) NOT NULL DEFAULT '0',
  `word` varchar(20) NOT NULL,
  PRIMARY KEY (`captcha_id`),
  KEY `word` (`word`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=71 ;

And you need to open system/application/config/database.php and modify it.

...
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root1";
$db['default']['password'] = "root";
$db['default']['database'] = "ci_captcha";
$db['default']['dbdriver'] = "mysql";
...

Autoload.php

Open system/application/config/autoload.php and change the line 44.

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

and line 54.

$autoload['helper'] = array('url');

Config.php

Open system/application/config/config.php and change the line 14.

$config['base_url']	= "http://127.0.0.1/ci_captcha/";

Modifying captcha_pi.php

Now open system/plugin/captcha_pi.php

By default, Captcha plugin generates 8 words in length. But if you want to change this length, 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);

I change to three words for my example.

$defaults = array('word' => '', 'word_length' => 3,
'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++)
</code>
which I changed to
<code>
for ($i = 0; $i < $word_length; $i++)

You need to change both line in order to work it properly.

Controller

Create a file
htdocs/ci_captcha/system/application/controller/myexample_captcha.php.
And paste the followings.

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

class Myexample_captcha extends Controller {
  function Myexample_captcha()
  {
    parent :: Controller();
  }
  function index()
  {
    /**
     * --SQL DDL
     *
     * CREATE TABLE captcha (
     * captcha_id bigint(13) unsigned NOT NULL auto_increment,
     * captcha_time int(10) unsigned NOT NULL,
     * ip_address varchar(16) default '0' NOT NULL,
     * word varchar(20) NOT NULL,
     * PRIMARY KEY `captcha_id` (`captcha_id`),
     * KEY `word` (`word`)
     * );
     */

    $captcha_result = '';
    $data["cap_img"] = $this -> _make_captcha();
    if ( $this -> input -> post( 'submit' ) ) {
      if ( $this -> _check_capthca() ) {
        $captcha_result = 'GOOD';
      }else {
        $captcha_result = 'BAD';
      }
    }
    $data["cap_msg"] = $captcha_result;
    $this -> load -> view( 'testcaptcha_view', $data );
  }
  function _make_captcha()
  {
    $this -> load -> plugin( 'captcha' );
    $vals = array(
      'img_path' => './captcha/', // PATH for captcha ( *Must mkdir (htdocs)/captcha )
      'img_url' => 'captcha/', // URL for captcha img
      'img_width' => 200, // width
      'img_height' => 60, // height
      // 'font_path'     => '../system/fonts/2.ttf',
      // 'expiration' => 7200 ,
      );
    // Create captcha
    $cap = create_captcha( $vals );
    // Write to DB
    if ( $cap ) {
      $data = array(
        'captcha_id' => '',
        'captcha_time' => $cap['time'],
        'ip_address' => $this -> input -> ip_address(),
        'word' => $cap['word'] ,
        );
      $query = $this -> db -> insert_string( 'captcha', $data );
      $this -> db -> query( $query );
    }else {
      return "Umm captcha not work" ;
    }
    return $cap['image'] ;
  }

  function _check_capthca()
  {
    // Delete old data ( 2hours)
    $expiration = time()-7200 ;
    $sql = " DELETE FROM captcha WHERE captcha_time < ? ";
    $binds = array($expiration);
    $query = $this->db->query($sql, $binds);

    //checking input
    $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
    $binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
    $query = $this->db->query($sql, $binds);
    $row = $query->row();

  if ( $row -> count > 0 )
    {
      return true;
    }
    return false;

  }

}//endofclass
/**
 * End of file example_captcha.php
 */
/**
 * Location: ./application/controllers/example_captcha.php
 */

?>

View

Create a file htdocs/ci_captcha/system/application/view/testcapcha_view.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title><?php echo $title; ?></title>
  <base href="<?=base_url();?>">
  </head>
<body>
<h2>Captcha Test</h2>
<form method="post">
<?php echo $cap_img ;?>
<p><?php echo $cap_msg ;?></p>
<input type="text" name="captcha" value="" />
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Test drive

Now visit http://127.0.0.1/ci_captcha/index.php/myexample_captcha to see your captcha.

captcha

6 comments to How to use Codeigniter captcha plug-in Part 1

  • very usefull tutorial.
    I have already implemented to my blog. thanks^^

  • [...] with CodeIgniter that will generate the captcha image, and I came across this excellent blog post http://www.okadadesign.no/blog/?p=276 with a guide to [...]

  • Very nice tutorial. I’ve rewritten this with a more mvc approach and added a custom validation function – you can see it here: http://tookertime.com/.

    One point on changing the string length to 3 – sometimes the letters end up outside the image. In the plugin you can see a line like this:

    $x = rand(0, $img_width/($length/3));

    when length is 3, it means the x co-ordinate of the start of the word can be as long as the image, so changing this to something like
    $x = rand(0, $img_width/($length/2));
    will be fine (assuming you don’t want a captcha of 2 or less letters). Not sure of the logic of that – it would make more sense to use the image width minus the spacing of the letters * the number of letters.

  • Misheck

    I have followed the tutorials but I am still getting “Umm captcha not work”. I have done all the relevant configuration but I am just stuck with that message.

  • shinokada

    @Misheck: I don’t think you created a captcha. Check your captcha folder if there are any created images.

  • Misheck

    Thanks “shinokada” I did not know that I had to create a folder for the captcha so after doing that everything worked ok. I only got a databse error because the value for

    ‘captcha_id’ => ”,

    is null so after removing it from the array it worked ok. thanks

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>