Thursday, January 29, 2009

Example of how to do CAPTCHA Php

Hey guys, thought I'd throw out a CAPTCHA example using GD for anyone who's wondered how they were done. This is just a simple basis for building a captcha image with php, nothing too fancy.

Features:

* TTF font usage
* Random from set of bg's
* Random colors for each char
* Random y-loc of chars
* Random angles of rotation for each char


//Start the session so we can store the key
session_start();

$font = "allstar.ttf";
$bgs = array("cap.png","cap2.png","cap3.png");
$bg = $bgs[rand(0,2)];

/*
* Generate a random string for captcha
*(doesn't matter how you do this)
* I just double md5'd microtime * a random int then randomly selected a length 5 char section of it
*/
$random = md5(md5(microtime() * rand(0,50)));
$string = substr($random,rand(0,27),5);

//Store the encrypted key in the session
$_SESSION['key'] = md5($string);

//Start the captcha image from one a fuzzy bg
$captcha = imagecreatefrompng($bg);

//Set the colors to use(RGB values)
$colors = array(imagecolorallocate($captcha, 0, 0, 0), imagecolorallocate($captcha, 192, 0, 0),
imagecolorallocate($captcha, 0, 0, 192), imagecolorallocate($captcha, 0, 192, 0),
imagecolorallocate($captcha, 226, 154, 0));

/*
* Now I write to the captcha image each char with the colors
* Using allstar.ttf font
* randomly generate angle
* randomly generate y-loc
* randomly generate color
*/
imagettftext($captcha, 18, rand(-25, 25), 10, rand(30, 40), $colors[rand(0,4)], $font, substr($string,0,1));
imagettftext($captcha, 18, rand(-25, 25), 35, rand(30, 40), $colors[rand(0,4)], $font, substr($string,1,1));
imagettftext($captcha, 18, rand(-25, 25), 60, rand(30, 40), $colors[rand(0,4)], $font, substr($string,2,1));
imagettftext($captcha, 18, rand(-25, 25), 85, rand(30, 40), $colors[rand(0,4)], $font, substr($string,3,1));
imagettftext($captcha, 18, rand(-25, 25), 110, rand(30, 40), $colors[rand(0,4)], $font, substr($string,4,1));

//Display the image
header("Content-type: image/png");
imagepng($captcha);
?>
From there all you need to do to utilize the captcha is create a form and test an md5'd post var against the session code. Enjoy, hope this is helpful to some.

Baldaris69[at]yahoo.com

No comments:

Post a Comment