◂ MK

Setting Up reCAPTCHA: I'm not a robot

Yesterday I was resolving an issue with the contact form on my front page. It works now, but if you have recently tried to contact me, I recommend trying again. Regardless, when I was working on it I was concerned about it's possible misuse, so I decided I can at least lower the risk by adding one of those new I'm not a robot reCAPTCHA buttons. I would prefer to keep my website as clean as possible, but the new captcha button is so easy for every user that I thought "why not", after all it could be good to learn anyways. And there comes in the selling point with the reCAPTCHA v2, simplicity and ease of use.

I'm not a robot dialog
The I'm not a robot dialog on my front page

When I began the process of implementing the button I was shocked by how easy it was for the developer as well. The button was a simple input on a form element. After that all it took was coding a simple POST request to Google, and back comes a simple and short JSON response stating whether the check was successful or not and three other bits of information. So I decided to write a step-by-step tutorial for any of you interested in using this.

It took only around 15 minutes to set up for the first time.

How to setup reCAPTCHA for your website with PHP

Here are the quick steps for setting up reCAPTCHA on your own site. This is only a very simple setup and not as secure as possible, but then again this won't be a serious security feature. Regardless, if you plan on using this on a big service, I recommend you to do some more steps for securing your website. Some tips for extra security can be found at the end of this article. For more comprehensive and advanced information visit the documentation. Now, let's get to it!

What you'll need

  1. Working PHP server
  2. Basic HTML and PHP skills
  3. Google account
  4. 15 minutes

1. Register your site on reCAPTCHA

The registration page can be found by entering the reCAPTCHA website and clicking Get reCAPTCHA or going straight through this link. All you'll need is a Google account to log in. Once logged in you'll just need to fill a tiny form as in the picture below. Only thing to note is that the Domains field needs the domains you'll use the captcha in, including localhost.

reCAPTCHA registration form

1.1 Keys

Next you'll land on a dashboard for your button. You'll find a section called Adding reCAPTCHA to your site. There you'll have two 40-character keys: a site key and a secret key. As the name should imply, the secret key is secret and you shouldn't let anyone find it.

2. Client side integration

This step should be very clearly copy-pasteable on the dashboard, but for the tutorial's sake I'll also copy it here.

Paste in the <head> tag
<script src='https://www.google.com/recaptcha/api.js'></script>
Paste in the <form> you want to use
<div class="g-recaptcha" data-sitekey="__YOUR-PUBLIC-SITE-KEY-HERE__"></div>

That's all you need to do on the client side. When the form is submitted, a string with the name g-recaptcha-response will be sent with the other form input. The server side part requires more coding by yourself but with this tutorial you'll get the most important code.

3. Server side verification

3.1 POST request

The last bit of work you'll have to do with the API is a quick POST request to the URL https://www.google.com/recaptcha/api/siteverify. With the request you'll have to send the secret code you were given earlier and the string you received with your form data. The full code will be at the end but if you want to write it yourself, here's a Stack Overflow question about doing a http request with PHP.

Decoding the response

Google will respond to your request with some data encoded in JSON format. With PHP you can decode JSON with the json_decode() function. Here's something the response could look like:

{ "success": true, "challenge_ts": "2017-07-29T13:18:43Z", "hostname": "localhost" }

or

{ "success": false, "challenge_ts": "2017-07-29T13:18:43Z", "hostname": "localhost", "error-codes": [ "timeout-or-duplicate" ] }

The only piece we'll be using is the success boolean, which simply states whether the user successfully completed the captcha. If not, it will also contain array error-codes which can contain any or many of the following codes:

There we have all the information needed for our setup. Now here's my completed code for the back end:

if(!isset($_POST['g-recaptcha-response'])){
    $error = true;
}else{
    $response = $_POST['g-recaptcha-response'];
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $key = 'INSERT YOUR SECRET KEY HERE';
    $data = array('secret' => $key, 'response' => $response);
    $options = array(
        'http' => array(
            'header' => "Content-type: application/x-www-form-urlencoded\r\n",
            'method' => "POST",
            'content' => http_build_query($data)
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if($result === false){
        echo 'Failed to contact reCAPTCHA';
    }else{
        $result = json_decode($result);
        if($result->success){}else{
            $error = true;
            echo 'The user failed to complete recaptcha';
        }
    }
}

4. Optional: Additional security

To help Google better detect cheaters you can send them an additional string called remoteip containing the user's IP address. You can also use the challenge_ts timestamp to be even more certain about the credibility. It's also recommended to check that the hostname response is your domain and/or remove localhost from the domains when no longer necessary. From the reCAPTCHA dashboard you can get analytics about your button.

I hope this article has helped you and be sure to share it and save it for the future!

#recaptcha #i'm not a robot #how to #tutorial #web development #security #php

Sources

www.000webhost.com