Search code examples
phpformscounterresetrecaptcha

PHP counter keeps resetting itself


So basically i have a form that submits information to my site where i can then later approve the information to go on my site or delete it.

I Recently added a recaptcha bot checker to the site so that i can avoid spammers and such but the problem is that i have the processes and the layout of the submit page in the same file(submitinfo.php)

The recaptcha process automatically kills the page because the captcha is not correct(because they didn't get a chance to type it) so i thought that instead of killing the page i will just make it come up with a message saying that the captcha is incorrect, but as stated above when the user first opens the page, they have not had a chance to enter the captcha and so the message will show even though they have not entered anything yet.

I thought if i add a counter that only shows a message if the counter is greater then 0 and adds +1 each time they load the page. I done that but the message does not show up even after getting the captcha incorrect several times, i think its because the counter resets every time i press the submit button. Here is the code so you guys can see what i have actually done:

$count

settype($count,"integer");

require_once('recaptchalib.php');
 $privatekey = "My Private Captcha Key goes here";
 $resp = recaptcha_check_answer ($privatekey,
                                 $_SERVER["REMOTE_ADDR"],
                                 $_POST["recaptcha_challenge_field"],
                                 $_POST["recaptcha_response_field"]);
// the stuff above is just the code from the captcha
 if (!$resp->is_valid) {
   // What happens when the CAPTCHA was entered incorrectly
   if($count>0){ $errormessage = "block"; //this displays the error message if the counter is greater then 0
   }
   $count++;

 } else{
    //here it submits the info

Solution

  • Just check that you have $_POST data before you check captcha. It should be something like this:

    <?php
    
    if ($_POST) {
        // check captcha
        if ($captcha_valid) {
            // persist submitted form data
            // redirect on success
        } else {
            $error = 'captcha';
        }
    }
    
    ?>
    <!-- display form -->