Random math captcha

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
implications
Forum Commoner
Posts: 25
Joined: Thu Apr 07, 2011 3:59 am

Random math captcha

Post by implications »

I've created a math captcha to my contact form by creating two variables and assigning random integers to them.

Code: Select all

$a = mt_rand(1,5);
$b = mt_rand(1,5);
$answer = $a + $b;
While echoing out $a and $b and the $answer variable gives out the right answer, I can't seem to validate the answer submitted via the contact form. The code looks something like this:

Code: Select all

$a = mt_rand(1,5);
$b = mt_rand(1,5);
$answer = $a + $b;

$antispam_a = clean($_POST['answer']);

if ($antispam_a != $answer) {
	$error = 'Wrong answer, try again.';
}

echo 'What is the sum of $a and $b?<br> <input type=\"text\" name=\"answer\">';
I've also tried storing the answer in a session and validating the session against the answer input but that didn't seem to work either.
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: Random math captcha

Post by egg82 »

I would go with the standard reCaptcha. It's easy to implement and free
outputting numbers directly to the browser somewhat defeats the purpose of a captcha
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Random math captcha

Post by twinedev »

What is the code you used for session? The code as you have it will not work as each time the page is called, as well as each time you submit it, you will have newly generated numbers.

If you already have session being used, I say go with storing it there. If not then another method would be to grab a set of functions like the int2key() and key2int() ones I posted on this sample code topic: viewtopic.php?f=1&t=132062

Using those, you can do:

Code: Select all

// For when the form is submitted

$antispam_a = clean($_POST['answer']);
$intAnswer = key2int($_POST['hash']);

if ($intAnswer==0 || $antispam_a != $intAnswer) {
				$error = 'Wrong answer, try again.';
}


// For generating form

$a = mt_rand(1,5);
$b = mt_rand(1,5);
$answer = $a + $b;

$antispam_a = clean($_POST['answer']);

if ($antispam_a != $answer) {
        $error = 'Wrong answer, try again.';
}

echo 'What is the sum of $a and $b?<br> <input type="text" name="answer">';
echo '<input type="hidden" name="hash" value="'.int2key($answer).'">';
Note, I call the hidden field "hash", as it is pretty undescriptive and doesn't indicate to someone doing view source (to try to write a bot to auto submit on you) that it actually contains the answer.

-Greg
Post Reply