Random Images for Form Validation
Inserting images with random character strings into your forms is an easy way to prevent robots from filling out your forms and flooding you with mail (or cluttering up your database). Here's how:
Save this as randomimage.php
<?php
Header("Content-Type: image/png");
session_start();
// Create a small image. Set foreground, background colors
$im = ImageCreate(200, 20);
$textcolor = ImageColorAllocate($im, 255, 255, 255);
$backgroundcolor = ImageColorAllocate($im, 0, 0, 0);
// Fill with backgroundcolor
ImageFill($im, 0, 0, $backgroundcolor);
// Generate a sequence of 6 chars. Don't use 0, O or Q.
$charlist = "123456789ABCDEFGHIJKLMNPRSTUVWXYZ";
$i = 0;
$length = 6;
$verf_string = "";
$printed_verf_string = "";
while ($i < $length) {
// pick a random character
$char = substr($charlist, mt_rand(0, strlen($charlist)-1), 1);
// don't reuse characters
if (!strstr($verf_string, $char)) {
$verf_string = $verf_string . $char;
$printed_verf_string = $printed_verf_string . $char . " ";
$i++;
}
}
// Write out the string
ImageString($im, 5, 50, 3, $printed_verf_string, $textcolor);
// Save it in the session global
$_SESSION['verf_string'] = $verf_string;
// output straight to browser.
ImagePNG($im);
ImageDestroy($im);
?>
Call this from your form, in order to display an image. In this case, the form is in a table:
<tr> <td><div align="right">Verification Code:</div></td> <td> <table><tr> <td><input name="form_string" type="text" id="form_string" size="6" /></td> <td><img src="imagepng.php" align="right" alt="Verification Image" /></td> </tr></table> </td> </tr>
Remember how we saved verf_string in random_image.php? Let's compare it to form_string, which the user fills in and submits on the form. We'll do this in the php that gets called when the user submits the previous form:
<?php
session_start();
$verf_string = $_SESSION['verf_string'];
....
$form_string = $_REQUEST['form_string'];
$form_string = trim($form_string);
$form_string = strtoupper($form_string);
if ($verf_string != $form_string){
die("Bad value for verification string");
}
In fact, we can be even more clever and use the session variables to prevent form re-entry:
<?php
session_start();
$verf_string = $_SESSION['verf_string'];
if ($_SESSION['last_verf_string'] == $verf_string) {
header("Location: index.php");
exit;
}
...
