If this blog helped you in any way, please donate a dollar here

Friday, August 6, 2010

Captcha in PHP

Writing a custom captcha for your website is a fairly easy task with the PHP GD Library.

The GD Library is a graphics library that enables to draw (and generate) graphics. This output can be done on any of the standard image file formats.

In my example I choose to create a PNG file that will be displayed in my registration page. So the first piece of code I need is somthing like this:

<img
src="captcha.php? echo rand(); ?>"
/>

Now the code:

echo
rand();

is required because, browsers can cache the image every time the form
is loaded. So to generate an unique captcha, the browser must first
request for a new image!



Now, to write captcha.php.



A very simple code would be:


<?
header("Content-type: image/png");

$im = @imagecreate(100, 25) or die("Captcha problem!");

$background_color = imagecolorallocate($im, 255, 255, 255);

$text_color = imagecolorallocate($im, 233, 14, 91);

$str = "";
$r = "";

for($i=0; $i<6; $i++ ) {
$r = chr( rand( ord('A'), ord('Z') ) ); break;
$str = $str . $r;
}

$_SESSION['captcha'] = $str;

$font = "./fonts/Arial.TTF";
$font_size = 16;
$font_theta = 0;
$x_off = 5;
$y_off = 20;
imagettftext($im, $font_size, $font_theta, $x_off, $y_off, $text_color, $font, $str);
imagepng($im);
imagedestroy($im);
?>

No comments:

Post a Comment