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