recaptcha

Disabling submission until reCAPTCHA verification passed doesn't work


I have a CakePHP website with a registration page and I am using google reCAPTCHA version 2 for the submission of the registration form. I have configured the page so that it doesn't submit until the reCAPTCHA has been solved but somehow I am still getting hundreds of registration emails submitted to my database. Here is the code I am using:

<div class='g-recaptcha' data-sitekey='6LchSJMpAAAAAOpvZFRoMM9WEHhMLARnsjNTRFBi' data-callback='enableBtn'></div>
<input type="submit" class="input_field button submit" onclick="LoginButton()" value="Register" disabled="disabled" id="button1"></div>
 function enableBtn(){
   document.getElementById("button1").disabled = false;
 }

LoginButton() is for verification of the reCAPTCHA submission


Solution

  • The spammers are bypassing the Google reCAPTCHA on the frontend and directly submitting the form to your server. This can happen because the reCAPTCHA validation is only happening on the client side, which is not secure. You need to validate the reCAPTCHA response on the server side to ensure its integrity. Google reCAPTCHA provides a server-side API to validate the token generated on the client side. Ensure your reCAPTCHA widget is correctly set up and includes a name attribute for the token.

    <div class="g-recaptcha" data-sitekey="6LchSJMpAAAAAOpvZFRoMM9WEHhMLARnsjNTRFBi"></div>
    <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
    <input type="submit" class="input_field button submit" value="Register" id="button1" disabled>

    In your PHP code, validate the g-recaptcha-response token with Google's reCAPTCHA API

    <?php
      if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      $recaptchaSecret = 'YOUR_SECRET_KEY';
      $recaptchaResponse = $_POST['g-recaptcha-response'];
    
      // Verify the reCAPTCHA response with Google's API
      $verifyURL = 'https://www.google.com/recaptcha/api/siteverify';
      $response = file_get_contents($verifyURL . '?secret=' . $recaptchaSecret . 
      '&response=' . $recaptchaResponse);
      $responseData = json_decode($response);
    
      if ($responseData->success) {
        // reCAPTCHA validation passed, process the registration
        // Insert user data into the database
      } else {
        // reCAPTCHA validation failed
        echo 'reCAPTCHA verification failed. Please try again.';
      }
    }
    ?>
    

    Replace YOUR_SECRET_KEY with the secret key from your reCAPTCHA configuration.