Monday, January 14, 2019

Using google reCAPTCHA with PHP



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.
Next you need to add the HTML along with your public key to the area you want the CAPTCHA to be displayed.
1
<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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if(isset($_POST['g-recaptcha-response'])) {
   // RECAPTCHA SETTINGS
   $captcha = $_POST['g-recaptcha-response'];
   $ip = $_SERVER['REMOTE_ADDR'];
   $key = 'PRIVATE KEY GOES HERE';
   // 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.

No comments:

Post a Comment