As we take a look on websites, we can easily see that most of them have contact form built in. But having this contact form could switch to huge amount of spam messages sent by using that form. Fortunatelly we can stop it using the Google reCAPTCHA on our website.
Register at Google reCAPTCHA site
First step to add Google reCAPTCHA to the website is to register your site at https://www.google.com/recaptcha/admin.
After filling up the form, we receive a pair of secret keys and some details about integration.
Implementation
As the first step of implementation we have to include reCAPTCHA JavaScript library on website.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Next step is to update our contact form. Just before the submit button we have to place following code, which will be responsible of rendering reCAPTCHA field.
<div class="g-recaptcha" data-sitekey="{Site key}"></div>
And that’s it on the frontend.
Let’s go to backend. Inside the logic which is responsible for form validation we have to add following snippet:
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])): //your secret key $secret = '{Secret key}'; //get verify response data $verifyResponse = file_ get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']); $responseData = json_decode($verifyResponse); if($responseData->success): //proceed the form fields validation and sending the e-mail else: //reCAPTCHA has not positive validation endif; else: //reCAPTCHA has not be chacked endif;
And that’s it. You can enjoy reCAPTCHA on your site and mailbox free of spam now.