Simple captcha

Spam! Urrrgggh! Want a ‘simple’ way of stopping spam in form submissions? Have a go at this, written by myself and used on quite a number of sites. Its simple – and works without relying on third-party-providers.

Create ‘image.php’ with the following content.

$img = imagecreate(48,25);
$backcolor = imagecolorallocate($img,153,0,0);
$textcolor = imagecolorallocate($img,255,255,255);
$number = $_GET['rand'];
header("Content-type: image/jpeg");

Just before the contact form, create the random number, and copy this to a session var….

$rand = rand(999,9999);
$_SESSION['rand'] = $rand;

…then enter the above image file in an image tag, like this:

Then submit the form and test

$Rand = trim($txtRand);
 if (strlen($Rand) <> 4) {

// display error and exit
 if (!($Rand == $_SESSION['rand'])) {
 echo ("Random number was incorrect.

Are you a SpamBot?

HOME"); exit; }

Leave a Reply