Page 1 of 1
Random math captcha
Posted: Sat Oct 08, 2011 9:18 am
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.
Re: Random math captcha
Posted: Sat Oct 08, 2011 3:11 pm
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
Re: Random math captcha
Posted: Sat Oct 08, 2011 6:20 pm
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