KB: Google reCAPTCHA Challenge Implementation

Front-end

1. Add the following to your HTML file to include Google's reCAPTCHA:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey="<PUBLIC_SITE_KEY>"></div>

The Google reCAPTCHA token will get automatically included when the form is submitted to your back-end. It will get stored in the "g-recaptcha-response" POST field. The token is the whole contents.

Back-end (PHP)

The Google reCAPTCHA token should be submitted along with the rest of the form, e.g. a registration form. The first thing you should do is to verify the reCAPTCHA token with Google. If this fails then return an appropriate error back to the user submitting the form, or process the rest of the submitted form data if the token is valid.

1. Create a function to process the verification of the reCAPTCHA token and return a boolean value indicating whether it is valid or not:

function VerifyGoogleReCaptchaToken($secret_key, $token)
{
    // make sure the token is a non-empty string
    if (!is_string($token) || !strlen($token))
    {
        throw new Exception("Missing token!");
    }

    // make sure the secret key is a non-empty string
    if (!is_string($secret_key) || !strlen($secret_key))
    {
        throw new Exception("Missing secret key!");
    }

    // verify with Google whether the given token is valid
    $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret_key."&response=".$token."&remoteip=".$_SERVER['REMOTE_ADDR']);

    // decode the response
    $g_response = json_decode($response);

    // is the token valid?
    return ($g_response->success === true);
};

2. In the code processing the submitted form data, call the above function with your secret key and the token submitted in the form ("g-recaptcha-response").

$valid = VerifyGoogleReCaptchaToken("<SECRET_SITE_KEY>", $token);
if ($valid)
{
    // process the form data submitted
}
else
{
    // reCAPTCHA verification failed
}

3. If the verification passes then continue and process the submitted form. If it fails, return an appropriate error back to the user.