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


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

<script src="" async defer></script>
   function YourOnSubmitFn(token) {

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>

Server side validation

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

function checkCaptcha(){    
        $captcha = $_POST['g-recaptcha-response'];
        $postdata = http_build_query(
                'secret'   => 'your-secret-key',
                'response' => $captcha,
                'remoteip' => $_SERVER['REMOTE_ADDR']
        $options = array('http' =>
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
        $context = stream_context_create($options);
        $result  = json_decode(file_get_contents('', false, $context));
        return $result->success;
        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…)

Comments are closed.