NerdyHearn
Home
Blog

Contact
Mailing List

Software

Active Directory Products
Object Compare
Permission Compare

IPhone Products
Calls To Calendar
SMS To CSV
SMS To Gmail
Voicemail To Gmail

Sites
DocuTerminal
How Long For Me
My Music To Me
SaveMySerials
TypeCount

Blog
Twitter

NerdyHearn - Blog


<< Back To All Blogs

A PHP Captcha Class

Tuesday, April 8th, 2008

A captcha is a very useful component to add to your blog to prevent SPAM bots from posting un-wanted garbage on your blog, or any other user-submitted form on your website.

I created a very simple Captcha class that can be used to create this image, the usage is posted below:

class Captcha {
var $session;
var $text;
var $width = 120;
var $height = 30;

function Captcha($session = "", $text = "", $width = 120, $height = 30) {
$this->session = $session;
if (empty($this->session)) {
$this->session = "captcha";
}
$this->text = $text;
if (empty($this->text)) {
$this->text = $this->getRandomText();
}
$this->width = $width;
$this->height = $height;
}

function getCaptcha() {
$_SESSION[$this->session] = $this->text;
$image = ImageCreate($this->width, $this->height);
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);

ImageFill($image, 0, 0, $black);
ImageRectangle($image,0,0,$this->width-1,$this->height-1,$grey);
imageline($image, 0, $this->height/3, $this->width, $this->height/3, $grey);
imageline($image, $this->width/3, 0, $this->width/3, $this->height, $grey);
ImageString($image, 4, 30, 3, $this->text, $white);
header("Content-Type: image/jpeg");
ImageJpeg($image);
ImageDestroy($image);
exit();
}

function getRandomText() {
$toReturn = "";
for ($a=0; $a<8; $a++) {
$rand = rand(97,122);
$toReturn .= chr($rand);
}
return($toReturn);
}
}

To use the captcha class to as follows:

Create a page called captcha.php, and on that page simply put the following:
$captcha = new Captcha();
$captcha->getCaptcha();

This will return a captcha image and set the session to the random text that is generated.

You can then reference this image as follows:
<img src="captcha.php">

Hopefully you'll enjoy the class, code away PHPers, code away...

Tom out.

Comments

Currently no comments.

Add A Comment

Name:


URL:


Email Address: (not public, used to send notifications on further comments)


Comments:



Enter the text above, except for the 1st and last character:


NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. DocuTerminal - Online Filing Cabinet solution. Scan, search and archive your paper documents. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers My Music To Me - Stream your subsonic music collection to your Sonos wireless system TypeCount - Count how often you type across different computers! ServrTrackr - Monitor your SSL certificates, website uptime, and DNS configurations