Add reCAPTCHA v2 to your website

4

You may want to protect your website forms from unwanted spam bots. There are many solutions to do this. Here is a how-to configure Google reCAPTCHA v2.

Sign into reCAPTCHA admin console

Register your website. Select “reCAPTCHA v2” and pick one of reCAPTCHA type. After that — copy two keys for your newly registered website: “Site key” and “Secret key”.

Now let's go edit some HTML and PHP. If you're not using PHP — it's OK. You'll easily understand what you need to do from the PHP code example.

First — we need to add reCAPTCHA to your HTML form:

<form method="post" action="/feedback" accept-charset="utf-8">
    <div class="form-group">
        <textarea name="message"></textarea>
    </div>
    <div class="form-group">
        <!-- reCAPTCHA will appear here. Put your Site key into the data-sitekey attribute -->
        <div class="g-recaptcha-custom" data-sitekey="XXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXX"></div>
    </div>
    <div class="form-group">
        <button>Submit</button>
    </div>
</form>

Second — put reCAPTCHA script before the closing </body> tag. You can specify reCAPTCHA language with hl parameter:

<script src="https://www.google.com/recaptcha/api.js?hl=en" async defer></script>

And the last — you need to validate reCAPTCHA test result on the server side where you handle your form's POST request:

# Put your Secret key here 
$secret_key = 'XXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXX';
$response = $_POST['g-recaptcha-response'];
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secret_key . '&response=' . $response;

$result = file_get_contents($url);

if($result === false)
{
    # Something is wrong - we didn't receive HTTP response 200
}

$result = json_decode($result);

if($result === null)
{
    # Something is wrong - the response is not valid JSON
}

if($result->success)
{
    # reCAPTCHA test has been successfully passed!
}
else
{
    # reCAPTCHA test has been failed
}

Done! Now your website is well-protected from spam bots.

Rate this post:
Share this page:

See also how to:

How to make POST and other types of HTTP requests and add custom HTTP headers with file_get_contents function in PHP
How to run your PHP or Bash script as root in the most secure way
How to use modern MaxMind GeoIP API in PHP
How to split YAML files and include them into each other with PHP
How to create a well-crafted RSS feed for a website and configure it property