reCAPTCHA on contact form

This tutorial will show you how to incorporate Google reCAPTCHA on your contact form to stop Internet bots from DDoS your mail server

You do not want to leave any submit form on your web site unprotected from Internet bots and spammers. Great tool for blocking Internet bots from submitting unusable information to your web server is using Google reCAPTCHA. 

As always, Google made incorporating reCAPTCHA in your web site relatively easy. 

Before we start with this tutorial, if you need help with creating simple contact form check my other tutorial: Send mail via PHP and AJAX

1. Registering your site at Google

Go to Google reCaptcha website and click on “My recaptcha”. 
Sign in to your Google account. If you do not have Google account, you will have to register at Google to use reCAPTCHA. 
After logging in, write label for this website key for easy managing if you are going to have multiple reCAPTCHA keys on same domain. Choose reCAPTCHA v2, accept reCAPTCHA Terms of Service and click Register.

Create new site at reCapthc Google
Create new site at reCaptcha Google

Google is going to create two keys, one public, Site key and one secret, Server key.

reCaptcha codes
reCaptcha codes

2. Integrating Google reCAPTCHA in website

To integrate reCAPTCHA on your web site copy and paste this line on the bottom of <head> tags on your web page


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

After pasting that line, copy and paste this line where you want reCAPTCHA widget to appear on your site.

<div class="g-recaptcha" data-callback="reCaptchaCallback" data-expired-callback="reCaptchaExpired" data-sitekey="publickey"></div>

Make sure you change “public key” string with your registered Site public key string.

In this tutorial we are not going to use server-side integration of Google reCAPTCHA. 
In this tutorial we want to stop Internet bots from DDoS our mail server, so reCAPTCHAs main goal is to enable/disable form submit button.
This tutorial is great example when you want to use reCAPTCHA with AJAX.

After creating reCAPTCHA widget we need to create two JS functions to enable form submit button after user passed the test, and function to disable form submit button after test expires.

This is submit button

<button id="submitBtn" type="button" onclick="sendMail()" class="btn btn-dark" disabled="true">Send</button>

This jQuery function enables form submit button after user pass the test.




This jQuery function disables form submit button after reCAPTCHA verification times-out.




Make sure to change identifier to correspond to your button id.

This is all you need for simple reCAPTCHA integration in your website. I hope this tutorial helped you with integrating reCAPTCHA in your website.