Keep Spambots Out with a Simple Math CAPTCHA
Spambots are undoubtably among the most annoying problems for web developers. They look for forms on your site, and submit links to their own websites, repeated many times and mixed with keywords. One way to deter them is a CAPTCHA (Completely Automated Public Turing Test to Tell Computers and Humans Apart). One common form of this is an image with distorted letters, and the user has to type in the letters. I find those really annoying, and unless you are very popular you probably don’t need something so difficult to crack. Our CAPTCHA will ask the user to answer an addition problem.
Part 1 is our register form, with a bit of PHP at the top.
<?php $n1 = rand(0, 10); $n2 = rand(0, 10); echo '<form action="register.php"> <table cellpadding="5" align="center"> <tr> <td> Username </td> <td> <input type="text" name="username" size="30"> </td> <tr> <td> Password </td> <td> <input type="password" name="pass" size="30 "> </td> </tr> <tr> <td> Bot Check </td> <td> '.$n1.' plus '.$n2.' = <input type="text" name="check" size="2" maxlength="2" />'.' </td> </tr> <tr> <td> Submit </td> <td> <input type="hidden" name="1" value="'.$n1.'" /> <input type="hidden" name="2" value="'.$n2.'" /> <input type="submit" value="Register" /> </td> </tr> </table> </form>';
It generates 2 random numbers between 1 and 10, and puts them in the form asĀ hidden inputs, while also displaying them to the user. This could be cracked in 20 minutes by a spambot programmer, but unless you get on CNN that’s not likely to happen.
The PHP code in register.php is a simple 2-liner.
if($_GET['1'] + $_GET['2'] != $_GET['check'])
die('You answered the bot check incorrectly.');
//Your registration code here
The script will add the two hidden form parameters, and compare them to the user’s answer. If they don’t match, the user can’t proceed.

August 14th, 2008 at 8:03 am
this is damn fool script… captcha has to be an image file, or something like flash, so you can not read easily by a script..
when you simply echo the values like that, it’s really easy to bypass this…
do something useful for ppl.. an avarage idiot can fake this
dont keep up your shit work

improve yourself
October 2nd, 2008 at 4:09 pm
i agree with the previous commenter. the script is a useless crap..
December 13th, 2008 at 6:19 am
For the comments above: if you don’t like it, don’t use it. if you think you can do better, then show us your work instead of demeaning others’ work.
May 16th, 2009 at 2:36 pm
MMM… and refresh image??
October 31st, 2009 at 10:46 pm
@ pdesign & sergey,
the author wrote:I find those really annoying, and unless you are very popular you probably don’t need something so difficult to crack.
so "those" refers to the image-based CAPTHCAs.
He intentionally wrote that "useless crap" (text CAPTCHA).
I totally agreed with Mohamed.