PHP Form Security Script

This script displays an image of a number that the user must type in correctly before they submit data from a form. The idea is to stop robots easily abusing your services such as automated posts to blogs and forums such as comment spam.

The main script generates an image of a random number and stores the number value in a session varaible. The code that runs after the form data is submitted, compares the number entered by the user with the number stored in the session variable to determine if a human rather than a robot submitted the form.

Save this code as gateway-image.php:

<?php
session_start();

$number = rand(1,999); //generate a random integer
$_SESSION['number'] = $number; //store in session variable
	 
$img_number = imagecreate(40,25);
$backcolor = imagecolorallocate($img_number,0xcc,0xcc,0xcc);
$textcolor = imagecolorallocate($img_number,255,255,255);

imagefill($img_number,0,0,$backcolor);

imagestring($img_number,10,5,5,$number,$textcolor);

header("Content-type: image/jpeg");
imagejpeg($img_number);
?>

Save this code as gateway.php (the html page with the form ):

<?php
session_start();
?>
<html>
<head>
<title>Gateway</title>
</head>
<body>
Please enter the value you see below:<br />
<img src="gateway-image.php" />
<form action="" method="post">
<input type="text" name="number" value="" /><br />
<button type="submit">Submit</button>
</form>
<?php
if (isset($_POST['number']))
  if ($_SESSION['number'] == $_POST['number'])
	   echo "Correct";
  else
	   echo "Wrong value entered!";
?>
</body>
</html>
logo
Webmaster Tools & Resources
Blog