0

I am unable to get my sessions captcha to work for some reason.

This is what I currently am trying.

$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];

This is what I have in my form

<form action="" method="post">
    <?=$_SESSION['n1']?> + <?=$_SESSION['n2']?> =
    <input name="captcha" type="text" class="text" />
<input name="submit" type="submit" /> 

For some reason it is always returning as the captcha being incorrect.

if($_SESSION['expect'] != $_POST['captcha']) {
   $err[] = 'The captcha answer is incorrect.';
}

3 Answers 3

2

Are those sessions being created on the same page the form is posting to? Maybe $_SESSION['expect'] is being overwritten with a new value. In that case, it wouldn't equal $_POST['captcha'].

4
  • I think you are right, just not sure where I would need to move the $_SESSION['expect'] so it won't be overwritten.
    – Jako
    Aug 5, 2011 at 20:33
  • 1
    You can do something like this: if (!isset($_POST['captcha'])) {//session code} Aug 5, 2011 at 20:38
  • Jason, that worked perfectly! Thank you so much, I figured it had to do with them being overwritten, just couldn't figure out an easy way to fix it. Thanks again!
    – Jako
    Aug 5, 2011 at 20:41
  • You could add a if(isset($_POST['captcha'])) to check if it's either creating a captcha or checking a captcha. In case it has failed, you can even create a new one. -- edit - oops just read you answered it
    – Filgera
    Aug 5, 2011 at 20:41
2

use that order:

if($_SESSION['expect'] != $_POST['captcha']) {
  $err[] = 'The captcha answer is incorrect.';
}

...

$n1 = rand(1,20);
$n2 = rand(1,20);
$_SESSION['expect'] = $n1 + $n2;

that way values will not be overwritten

3
  • and what difference will that make?
    – wonk0
    Aug 5, 2011 at 20:30
  • Jacek, just by swapping out what I had with your code I still seem to be getting the same results.
    – Jako
    Aug 5, 2011 at 20:31
  • then check what is the value of $_SESSION array on the start of your script Aug 5, 2011 at 20:34
1

The session is being started, either by session_start() or by session.auto-start-directive?

And are you sure the session id is being passed?

2
  • It is being started by session_start(). Should I put the session numbers in the form rather than in the head of the document? I figure like someone said above that the numbers are changing once the form is submitted which is why they do not match up.
    – Jako
    Aug 5, 2011 at 20:32
  • 1
    of course you should compare the submitted values to the ones stored in the session before assigning new ones
    – wonk0
    Aug 5, 2011 at 20:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.