Optimisations

Prevent spam bots from spamming your website' contact form by integrating Google's Recaptcha

Register your website

To be able to make use of Google's Recaptcha you'll need to add your website to the admin panel of Google Recaptcha and generate the SITE_KEY and the SECRET_KEY

  1. Go to https://www.google.com/recaptcha/admin and add your domain.
  2. Select reCAPTCHA type, it's up to you but in this example we use reCAPTCHA v2, the checkbox version.
  3. Add your domain (fe. web-hints.com)

After these steps and validation of the form, you'll be granted with a two keys which we will use in the next step.

Frontend integration

Add the following within your form element, right above the submit button might be an excellent position.

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

Don't forget to replace the <<SITE_KEY>> with your actual site key generated in the previous step.

Backend integration

When form will be submitted a input field with name g-recaptcha-response will contain a special string to verify with Google if the user is a bot or not. 

We take this string and send it for validation to Google.

$recaptchaResponse= $_POST['g-recaptcha-response'];

$url = 'https://www.google.com/recaptcha/api/siteverify';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'secret' => '<<SECRET_KEY>>',
    'response' => $recaptchaResponse,
    'remoteip' => $_SERVER['REMOTE_ADDR']
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response, true);

if ($response['success'] !== true) {
    //-- Do something when reCAPTCHA is invalid
}

Don't forget to replace <<SECRET_KEY>> with the one generated in the first step.

If you now visit your page you should see the reCAPTCHA button, if you have issue implementing please comment below and I'll try and help you out.

Interested in more articles about Optimisations?