Simple PHP Captcha

I came across this bit of code while I was looking for some reference material to help out a classmate with his PHP homework and thought I'd share.

All this does is generate a (basic) captcha image and check the user-inputed value. It's a good exercise for learning the GD library and some basic session stuff.

The code is split up in to two files: one for the HTML form, and the other for generating the image itself.

<?php

session_start();

function new_capt() {
	$md5 = md5(microtime() * mktime()); 
	$string = strtolower(substr($md5,0,5));
	$_SESSION['captcha'] = $string;
	return $string;
}

if( $_POST['txt'] ) {
	if( strtoupper($_POST['txt']) == $_SESSION['captcha'] ) {
		echo 'Match<br />';
		echo new_capt();
	} else {
		echo 'No match<br />';
		echo new_capt();
	}
} else {
	echo new_capt();
}

?>

<hr />
<img src="image.php" />

<form method="post" action="#">
<input type="text" name="txt" />
<input type="submit" value="Go" />
</form>
<?php

session_start();
$text = strtolower($_SESSION['captcha']);
$font = './BaroqueScript.ttf';
$imgX = 200;
$imgY = 100;

// center info for the text
$tbox = imagettfbbox(20, 0, $font, $text);
$xcent = ($imgX - $tbox[4]) / 2;
$ycent = ($imgY - $tbox[1]) / 2;

$im = imagecreatetruecolor($imgX,$imgY);
imageantialias($im, true);

// the colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
$pink = imagecolorallocate($im, 242, 12, 115);
imagefilledrectangle($im, 0, 0, $imgX, $imgY, $white);

//	     size, angle, x, y
imagettftext($im, 20, 0, $xcent, $ycent, $pink, $font, $text);

// draw some random lines
for( $i = 0; $i < 5; $i++ ) {
	$col = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
	imagesetthickness($im, 4);
	$x1 = rand(0,$imgX);
	$y1 = rand(0,$imgY);
	$x2 = rand(0, $imgX);
	$y2 = rand(0, $imgY);
	imageline($im, $x1, $y1, $x2, $y2, $col);
}

// send out the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

Demo here, DL here.
You can find the font used in this script over here, or use your own.

Tags: