Search code examples
phprecaptcha

How do I verify recaptcha response test in server request method?


I have the code from below, once the form is sended I want to check in it if the user passed the recaptcha test. How do i do it? Searched many things and i can't find a way that works for me ..

<html>
  <head>
        <script type="text/javascript">
        
        var verifyCallback = function(response) {
           alert(response);
        };
    
          var onloadCallback = function() {
            grecaptcha.render('example3', {
              'sitekey' : '6LdlRIgaAAAAAJXOu3EsuGVnKVjmSaWfSbuwSHLI',
              'callback' : verifyCallback,
              'theme' : 'dark'
            });
          };
          
        </script>
  </head>

  <body>
      
      <?php
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            // here I want to verify if the use user passed the recaptcha
            {
                some code
            }
        }
      ?>
 
    <form method="POST">
      <div id="example3"></div>
      <br>
      <input type="submit" value="Submit">
    </form>
    
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
        async defer>
    </script>
    
  </body>
</html>

Solution

  • You should lookup the Server side validation docs for reCAPTCHA: https://developers.google.com/recaptcha/docs/verify

    You have to send an API request via PHP CURL, as stated in the docs:

    URL: https://www.google.com/recaptcha/api/siteverify METHOD: POST

    So something like this:

    function validate_captcha($secret, $response, $remoteip) {
    
        $captcha_url = "https://www.google.com/recaptcha/api/siteverify";
        $captcha_url .= "?secret=".$secret;
        $captcha_url .= "&response=".$response;
        $captcha_url .= "&remoteip=".$remoteip;
        
        $ch = curl_init($captcha_url);
    
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        $data = curl_exec($ch);
        
        curl_close($ch);
         
        $response=json_decode($data,true);
        
        if ($response["success"]) {
            return true;
        }
        else {
            return false;
        }
    
    }
    

    And you call the function like this:

    $captcha_is_ok = validate_captcha(
      "......mySecret.....", 
      $_POST['g-recaptcha-response'],
      $_SERVER['REMOTE_ADDR']);
    
    if ($captcha_is_ok) {
      ... do something cool ...
    } else {
      ... don't do something cool ...
    }