Eliaslog.pw

If you want to get rid of spam and are fine with helping Google to train their image algorithm for free, Google ReCaptcha is a good way to combat unwanted entries on your webform.

In this post we’ll go over four simple steps (with code!) how to implement Google ReCaptcha v2.

Step 1: Get your credentials

Google needs to check, that the site requesting a recaptcha validation is really your site. For this you’ll need two keys: the “websitekey” and the “secret key”. To get both you need to register your site to have a recaptcha field.

Go to https://www.google.com/recaptcha/admin/create and login to your Google account. After filling out the form (make sure you select “ReCaptcha v2”), you’ll receive both keys.

Step 2: Include the JS-Library

First you’ll need to implement the JS-Library provided by Google. It will insert the Checkbox and conditionally the image-test to check for robots.

https://www.google.com/recaptcha/api.js

You can either paste it as script-tag in the header or include it in your bundle.

Step 3: Determine where to display the checkbox

To put the infamous checkbox in a specific place, just drop in the following line (usually right in front of the submit-button):

<div class="g-recaptcha" data-sitekey="___websitekey___"></div>

The class-name makes sure that the JS we’ve implemented earlier knows where to insert the checkbox. For the “sitekey” data-attribute we use the websitekey provided in step 1.

Step 4: Send a verification request to Googles API

You can choose your preferred way to send a request to https://www.google.com/recaptcha/api/siteverify.

The parameter that have to be included in the request are the secret-key and the $_POST['g-recaptcha-response'] variable that will be injected into the form-submission by the JS-Library from step 2.

For this quick walk-through I’ll use PHP.

$requestparams = '';
$params = array(
    'secret' => '__secret_key__',
    'response' => $_POST['g-recaptcha-response']
);

foreach($params as $key=>$value) {
	$requestparams .= $key . '=' . $value . '&';
	$requestparams string = rtrim($requestparams, '&');
}

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($curl, CURLOPT_POST, count($params));
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestparams);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);

$result = curl_exec($curl);
curl_close($curl);

$check = json_decode($result, true);

Exchange the secret_key with the secret key provided in step 1.

If the resulting variable $check contains the key success (ie. $check['sucess']) the form submission was approved and you can invoke your mail-function or else.

If the success key is not present, the user probably forgot to check the box. You should remind him to do so ;).

The creation of this post was made possible by coffee.
Buy me a coffee