Advertisement
PHP

Adding reCAPTCHA with PHP

Post image

One of the best ways to stop contact form spam on your website is by implementing a CAPTCHA or RECAPTCHA. These are simple checks that verify whether the user is real or a bot before sending you the mail.

This tutorial will take you through how to add the Google reCAPTCHA to your PHP form, preventing spammers contacting you or submitting false data.

Getting Started

Before you start coding you need to sign up on Google to get your own API credentials - click here to sign up.

reCAPTCHA Base Code

Once you've signed up you'll need to add the reCAPTCHA Javascript to your page between the <head> tags.

<script src='https://www.google.com/recaptcha/api.js'></script>

Next you need to add the HTML along with your public key to the area you want the CAPTCHA to be displayed.

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

Simple so far.

reCAPTCHA PHP Code

reCAPTCHA is a multi-language solution, so you can do this next bit in the language the rest of your code is created in. For this tutorial I'll be showing the PHP solution.

<?php
if(isset($_POST['g-recaptcha-response'])) {
   // RECAPTCHA SETTINGS
   $captcha = $_POST['g-recaptcha-response'];
   $ip = $_SERVER['REMOTE_ADDR'];
   $key = 'PRIVATE KEY GOES HERE';
   $url = ''https://www.google.com/recaptcha/api/siteverify';

   // RECAPTCH RESPONSE
   $recaptcha_response = file_get_contents($url.'?secret='.$key.'&response='.$captcha.'&remoteip='.$ip);
   $data = json_decode($recaptcha_response);

   if(isset($data->success) &&  $data->success === true) {
       // code goes here
   }
   else {
      die('Your account has been logged as a spammer, you cannot continue!');
   }
}
?>

The code starts by checking whether the captcha response has been sent via POST data, if it has then continue. Next we outline the reCAPTCHA settings, including the private key.

With all the settings defined we send them to Google to get the response using file_get_contents(). This response will come back encoded in json format, that means we need to use json_decode() to decode it.

Now we have the response we can check whether the reCAPTCHA has been successful. If the verification has been successful then continue with your code, if not return an error message.

Conclusion

This article has taken you through the very simple PHP and HTML code for adding a reCAPTCHA to your website. With reCAPTCHA you will protect your website from spam and abuse while letting real people pass through with ease.

Advertisement
You may also like:
comments powered by Disqus