How to prevent bots spamming your forms

Today I’m going to explain how you can prevent bots submitting spam to your online contact forms, registrations and submission forms in general. We will use PHP and GD to achieve this. The following is the code for the image.php script with the comments where needed.

<?// First things first we start session

session_start();

// We generate unique confirmation code from the time this script is executed and taking the md5 of that.

$md5 = md5(microtime() * mktime());// Since MD5 hash will produce you 32 character long string, we will have to cut it down to 5 digits and make all caps for the users convenience.

$string = strtoupper(substr($md5,0,5));

// We will here write the confirmation code into session and pass it to the next page

$_SESSION['key'] = md5($string);

// Here we show which PNG file to use as the background and write the code on top of our PNG image

$captcha = imagecreatefrompng(”captcha.png”);

$black = imagecolorallocate($captcha, 0, 0, 0);

imagestring($captcha, 233, 20, 10, $string, $black);

// Finally we present the generated image to the browser as PNG image.

header(”Cache-Control: no-cache, must-revalidate”); // HTTP/1.1

header(”Expires: Mon, 26 Jul 1997 05:00:00 GMT”); // In the past

header(”Pragma: no-cache”);

header(”Content-type: image/png”);

imagepng($captcha);

?>

captcha.png

This is the background I used for my example. I made some photoshop brush ups if the bots try to read the text on the image. This will hopefully give them difficulties reading it.

Now, inside your form tag display the image and add additional text field and name it code like this:

<?
if(md5($_POST['code']) != $_SESSION['key'])
{
echo “Wrong confirmation code!”;
exit;
}
?>

Now I believe this is very much basic way of using CAPTCHA, but for those who needs a solution that is easily done without much of coding and digging this might be a handy thing.

I will try to enhance and optimize where possible and update you with the sample codes as downloads.

Comments

2 Responses to “How to prevent bots spamming your forms”

  1. jusupov.com » Free fonts for your applications on May 9th, 2007 11:23 am

    [...] need different fonts to be used then the usuals. Be it just navigation buttons, site slogan or a CAPTCHA code. At Urban Fonts you can download free fonts for your usage, or if it is not enough you can [...]

  2. Know how to present - jusupov.com on May 22nd, 2007 3:39 am

    [...] any contact form, you must implement some sort of human checking methods. You can read more about captcha tutorial, Why server side validation is important or why spammers love JavaScript [...]

Leave a Reply

You must be logged in to post a comment.

Categories


Clicky Web Analytics