Captcha Images
Saturday, April 28, 2007
Whenever a website/webservice goes popular, it attracts more spam content. Automated Scripts are deployed to create many accounts with that Site, and used for Spamming purposes or activities that were not intended to take place there.
Captcha ("Completely Automated Public Turing test to tell Computers and Humans Apart", hey this has been trademarked by CMU) has been able prevent automated software from performing actions which degrade the quality of service of the system, whether due to abuse or resource expenditure. CAPTCHAs are designed to be unreadable by machines.
The above image is Captcha Image. Well let us now how we can make such images, containing Random text.
Steps :
1 ) Create random lines and dots in the background.
2 ) Generate some random text.
3 ) Print each letter of the text into the Image in a random angle (say between -300 to 30o )
4) Save the random text in your Session and then output the image to the browser.
5) When the form is submitted and processed, check whether the text entered by the User and the text in Session Variable are the same.
And thats it. Done.
Now let us look at the PHP Code used to create the above image.
generateCode($characters);Enjoy.
/* font size will be 75% of the image height */
$font_size = $height * 0.4;
$image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
/* set the colours */
$background_color = imagecolorallocate($image, 0, 0, 0);
$text_color = imagecolorallocate($image, 230, 210, 150);
$noise_color = imagecolorallocate($image, 70, 70, 180);
/* generate random dots in background */
for( $i=0; $i<($width*$height)/5; $i++ ) { imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color); } /* generate random lines in background */ for( $i=0; $i<($width*$height)/350; $i++ ) { imageline($image, mt_rand(10,$width), mt_rand(80,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color); } /* create textbox and add text */ $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
$x = (($width - $textbox[4])/2)-35;
$y = (($height - $textbox[5])/2);
for ($i=0;$i<$characters;$i++) { imagettftext($image, $font_size, mt_rand(-25,25), $x+($i*30), $y, $text_color, $this->font , substr($code,$i,1)) or die('Error in imagettftext function');
}
/* output captcha image to browser */
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
$_SESSION['security_code'] = $code;
}
}
$width = isset($_GET['width']) ? $_GET['width'] : '200';
$height = isset($_GET['height']) ? $_GET['height'] : '60';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '6';
$captcha = new CaptchaSecurityImages($width,$height,$characters);
?>
Posted byShyam at 1:40 PM