Captchas are used to automatically distinguish between humans and computers/bots. They are useful in publicly available forms on a site to stop bots from automatically filling your forms out with crap you don’t want.
I have devised this simple class to generate a random string which is stored as a session vaiable. An image of the random string is then created which can be displayed on a page and a user can be asked to enter the characters they see in the image into a text field. The idea is that a bot won&rsqo;t be able to read the characters displayed on the image which are easily distinguishable be a human.
This method of authenticating user submitted content is useful and can be used along with spam detection techniques, timeout mechanisms and/or content approval - which I use on this site.
The class definition I have included below is quite a simple implementation and you may want to customize it your own way.
For more information on captchas you can read about them on the official captcha site.
+ –
<?php
/*requires the php GD graphics library turned on to make the image. Also requires sessions*/
class ImageCaptcha
{
private $captcha_length = 3;
private $case_sensitive = false;
public function set_captcha()
{
//Edit to change characters that can be used to create the captcha img
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$chars .= "abcdefghijklmnopqrstuvwxyz";
$len = strlen($chars) - 1;
$string = "";
for($i = 0; $i < $this->captcha_length; $i++)
{
$pos = mt_rand(0, $len);
$string .= substr($chars, $pos, 1);
}
$_SESSION['CAPTCHA'] = $string;
}
//call this function in a separate file and just include/require it in the relevant form
public function print_captcha_image()
{
header ('Content-type: image/png');
$im = @imagecreatetruecolor(100, 30)
or die('Cannot Initialize new GD image stream');
$bg = imagecolorallocate($im, 255, 255, 255); //bg color white
imagefilledrectangle($im, 0, 0, 100, 30, $bg);
$text_color = imagecolorallocate($im, 0, 0, 0); //text color black
imagestring($im, 5, 5, 5, $_SESSION['CAPTCHA'], $text_color);
imagepng($im);
imagedestroy($im);
}
//compares the passed parameter value with the captcha value set and returns true if they match
public function validate_captcha($submitted)
{
$set_captcha = str_replace(" ", "", $_SESSION['CAPTCHA']); //remove whitespace in the captcha
if(!$this->case_sensitive)
{
$submitted = strtolower($submitted);
$set_captcha = strtolower($set_captcha);
}
//unset the captcha as a precaution
unset($_SESSION['CAPTCHA']);
if($submitted == $set_captcha)
return true;
else
return false;
}
}
?>
Comments (0)
+ –