MaggsWeb:7

www.maggsweb.com

Simple captcha

October 4, 2007 | Comments | PHP

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);
imagefill($img,0,0,$backcolor);
$number = $_GET['rand'];
Imagestring($img,10,5,5,$number,$textcolor);
header("Content-type: image/jpeg");
imagejpeg($img);

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:

<img src="/image.php?rand=$rand;" />

Then submit the form and test

$Rand = trim($txtRand);
 if (strlen($Rand) <> 4) {
 
// display error and exit
 exit();
 }
 if (!($Rand == $_SESSION['rand'])) {
 echo ("Random number was incorrect.<br/><br/>Are you a SpamBot?<br/>
 
<br/><a href='/' onfocus='blur()'>HOME</a>");
 exit;
 }
Share this:
  • Print
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • LinkedIn
  • Twitter

Write a Comment

Let me know what you think?