Need help with PHP and MYSQL math captcha failing answer validation!

I want to create a fairly simple math captcha that randomly outputs a math question, then stores the answer in the DB along with a unique ID for the user. This all works, but for some reason, no matter what answer I give when testing, it always fails and says “wrong answer”. I got the same error when doing it with sessions (weird?). I prefer mysql though. I’m at wits end. If anyway could help, I’d greatly appreciate it! Here is the full code: php captcha - Pastebin.com

Thanks!

$captchaId = time();
$_SESSION[‘captchaId’] = $captchaId;

Your logic doesn’t work because you are generating and storing a new value in the session variable every time the page is requested. You would only generate a new value and store it in the session variable if the session variable isn’t set.

Note: multiple users can request your page in the same second. Using time() isn’t unique. Use the session_id() instead.

The session variable is also a ‘required’ input to your form processing code. You must validate it before using it. If it’s not set, that’s an error, e.g. someone submitted form data to your code without first visiting the form.

Okay, thanks! Do you suggest using the DB still, or switch back to session variables, which was my first approach?

Just store the answer in a session variable.

The code for any page should be laid out in this general order -

  1. initilization
  2. post method form processing
  3. get method business logic - get/produce data needed to display the page
  4. html document

The code to generate the math question and store the answer in a session variable belongs in item #3 on this list.

Got it working. I started over from scratch. Thanks for the info!

Sponsor our Newsletter | Privacy Policy | Terms of Service