Board logo

subject: Captcha for Codeigniter [print this page]


Captcha for Codeigniter
Captcha for Codeigniter

Recently, I have been playing around with different frameworks. My team and I actually came up with our own MVC (Model View Controller) framework and used it in one of our projects. That is when I discovered Code Igniter.

Well, for those of you who do not know it, it's one of the many available PHP frameworks out there. Why did I choose this you might ask? Well its easy to use and configure. And it has very useful helpers and a good set of library. And its quite fast.

Anyway, I am building several personal websites using code igniter. (Almost 2 weeks using/learning this framework) and I wanted to integrate a captcha in my registration form. (For those who do not know what a captcha is, it's the random alphanumeric characters you see in your websites to verify if you are human or not). I know code igniter has a plugin for captcha but for the fun of it I wanted to create my own and made it a model for now. Its still on its version 0.1a. I haven't had time to make it modular or clean up the code, but it is doing its job so all is good.

Here is the requirements you need to run my captcha script:

1. Code Igniter framework (click here)

2. GD installed on your webserver

3. Session library is enabled on your ci controller or autoload

Captcha Model:

filename: captcha_model.php (save in Model folder)

class captcha_model extends Model

{

function captcha_model()

{

parent::Model();

}

function generateCaptcha()

{

$size=20;

$minAngle=1;

$maxAngle=5;

$horizontal=10;

$vertical=28;

$font= "arial.ttf";

$bg = base_url()."i/captcha/white110.png";

$RandomStr = md5(microtime());

$ResultStr = substr($RandomStr,0,6);

$NewImage =imagecreatefrompng($bg);

$TextColor = imagecolorallocate($NewImage, 0, 0, 0);

$color = $TextColor;

$text = $ResultStr;

imagettftext($NewImage, $size, rand(-$minAngle,$maxAngle), $horizontal, $vertical, $color, $font, $text);

$newdata=array('captcha_key'=>$text);

$this->session->set_userdata($newdata);

header("Content-type: image/jpeg");

imagepng($NewImage);

imagedestroy($NewImage);

}

}

How to include it on your codeigniter library:

Create a captcha controller like this:

So everytime you want to generate a captcha image you just point it as http://yourdomain.com/captcha

My form looks like this:

Message:

Validation Code:




welcome to loan (http://www.yloan.com/) Powered by Discuz! 5.5.0