How to implement Google Invisible reCaptcha in PHP

Google recently introduced the Invisible reCAPTCHA, which hides Captcha challenge from view and makes it even simpler for website’s users to fill in a form.

Official documentation can be found here. The below is an example of how to implement it on a PHP website.

Get the Keys required

First, get Site Key and Secret Key by logging into your Google account and registering your website at https://www.google.com/recaptcha/admin

Frontend

Paste the following code in the section of your html template.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
   function YourOnSubmitFn(token) {
     	document.getElementById("your-form-id").submit();
   }
</script>

Replace your form’s Submit button with the code below.

<button class="g-recaptcha" data-sitekey="your-site-key" data-callback="YourOnSubmitFn">Submit</button>

For example

<form id="your-form-id" action="someActionUrl" method="post">
    ...
    <button class="g-recaptcha" data-sitekey="your-site-key" data-callback="YourOnSubmitFn">Submit</button>
</form>

Server side validation

To verify reCaptcha response in PHP, I created the following function.

function checkCaptcha(){    
    if(isset($_POST['g-recaptcha-response'])){
        $captcha = $_POST['g-recaptcha-response'];
 
        $postdata = http_build_query(
            array(
                'secret'   => 'your-secret-key',
                'response' => $captcha,
                'remoteip' => $_SERVER['REMOTE_ADDR']
            )
        );
 
        $options = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
 
        $context = stream_context_create($options);
        $result  = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context));
 
        return $result->success;
    }else{
        return false;
    }
}

3 thoughts on “How to implement Google Invisible reCaptcha in PHP”

  1. Hi,
    thank you for this explication but I don’t where to put the server side validation, I guess in my php page which verify and validate previously the form before sending ?
    (sorry because my poor English…)

Leave a Reply

Your email address will not be published. Required fields are marked *