Sunday, October 23, 2011

PHP Captcha Class Using Session Variable

Following php class will generate a captcha at runtime using random numbers assigned to session variable and display it as an image.
Captcha generated using this class


// Set the content-type
session_start();


header('Content-Type: image/png');


// Create the image
$im = imagecreatetruecolor(180, 40);


// Create some colors
$white = imagecolorallocate($im, 255, 248, 201);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 135, 85, 70);
imagefilledrectangle($im, 2, 2, 178, 38, $white);


// The text to draw
$text = $_SESSION['secure'];
// Replace path by your own font path
$font = 'nyala.ttf';


// Add some shadow to the text
imagettftext($im, 35, 0, 0, 0, $black, $font, $text);


// Add the text
imagettftext($im, 38, 0, 20, 30, $black, $font, $text);


for ($i = 1; $i <= 150; $i++) {
    $x1=rand (1,180);
$y1=rand (1,180);
$x2=rand (1,180);
$y2=rand (1,180);
imageline($im ,$x1,$y1,$x2,$y2, $black);
}
$rey2 = imagecolorallocate($im, 255, 248, 201);


for ($i = 1; $i <= 30; $i++) {
    $x1=rand (1,180);
$y1=rand (1,180);
$x2=rand (1,180);
$y2=rand (1,180);
imageline($im ,$x1,$y1,$x2,$y2, $rey2);
}
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>



Save the above file with the name generate.php or any other name you like.


How to call this Class 
In the page you want add this captcha,add following code to header



session_start();
if (!isset($_POST['secure'])) {
$_SESSION['secure'] =rand(100000, 999999);
}

and in img tag src call to
src="generate.php"