Create A Captcha Form

Posted by Pete | Posted in PHP Tutorials | Posted on 11-08-2009-05-2008

2

This tutorial will teach you how to protect your form’s from being submitted by bots. We will use a simple way, by creating a image using php with some randomly generated numbers then store it as a session and when the form is submitted we will check if the field in the form matches up with the numbers generated.

So lets create the image and the random numbers.
image.php

<?php
session_start(); // Start Sessions
 
$string = ""; // Set $string to blank
$i = 0; // Set $i as 0
WHILE ($i < 5){ // If $i is smaller than 5 run the following
	$string .= rand("0", "9"); // Generate a random number between 0 and 9 and add it to $string
	$i++; // Increase $i by 1
}
$_SESSION['rand_code'] = $string; // Assign $string to $_SESSION['rand_code']
 
 
// Create a 100 by 30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string to the image with the textcolor as set above
imagestring($im, 5, 25, 7, $string, $textcolor);
// Set the page header type as a png file
header('Content-type: image/png');
// Create the png
imagepng($im);
// Close the image creation
imagedestroy($im);
?>

Now we have the image we need to create the form.

form.php

<?
session_start(); // Start Sessions
if($_POST[submit]){ // Check if submit button has been pressed
	if($_POST[human] == $_SESSION['rand_code']){ // Check if human form field equals $_SESSION['rand_code'];
		// Put your form submittion stuff here
		echo "You are a human"; // Echo message
	}else{ // If code is incorrect
		echo "Naughty Bot."; // Echo message
	}
}
?>
<form method="POST">
	<br />Are You Human:<br />
	<img src="image.php" /><br />
	<input type="text" name="human" size="20"/><br />
	<input type="submit" value="Submit" name="submit"/>
</form>

And thats it. Not as hard as you first thought hey :P For more information about GD and creating an image using PHP visit http://uk.php.net/manual/en/ref.image.php. Should you have any more questions please leave a comment and any feedback you have.

Comments posted (2)

Hi,

Thanks for your great effort!

However, I might have done something wrong somewhere (MAY Be) but there is no validation taking place only a new number is generated.

Pleaz advise

What is happening is there is a image generated with a random number. This number is then stored in a session and then in the form you must enter the number into the field that is on the image. But obviously bots are unable to view the numbers on the image so they cant complete the form and once the form has been submitted we check if the number matches and if it doesn’t match then that means its a bot etc.

Write a comment

You must be logged in to post a comment.

Tutorials Written By Peter Kelly