How to Add ReCAPTCHA V3 to PHP Form and Submit Using Ajax

How to Add ReCAPTCHA V3 to PHP Form and Submit Using Ajax

In this tutorial, we will add Google reCAPTCHA v3 to a PHP form and submit it without leaving the page, using Ajax. If you have had a contact form or any such form on your website, you know how annoying it is to receive spam messages from bots. Google reCAPTCHA protects you from spam and other automated abuse. To follow along this tutorial, you need to have some basic knowledge of HTML, jQuery and PHP. Why Google reCAPTCHA v3? We have all had the frustrating experience of trying to quickly submit some information through a form only to be faced by a Captcha challenge in the end. We’ve had to type in random characters and wondered, “Is that two Vs or a W?”, “Should I add that space or not?”. And then we’ve had to select all the images that have zebra crossing or bridges to prove that we are humans. Thankfully, these days, a lot of websites have added Google reCAPTCHA v2 which just displays a checkbox – “I’m not a Robot”. However, in 2018, Google released the next version – reCAPTCHA v3 which doesn’t need any user interaction at all. It works behind the scenes observing the user’s behavior. This version provides us (developers) with a score that indicates how suspicious an interaction is. We could use that score and prevent spam. Read how it works at Google’s official webmaster blog. Now let’s learn how to add this to a simple form. Register reCAPTCHA v3 keys You need to first register your website and get the keys here – Add a label, select reCAPTCHA v3, type your domain name(s) and submit. This will generate a “site key” and a “secret key”. Copy both and keep them safe. We will need them soon. HTML Form Let’s take a simple contact form with Full name, Email and Message fields The HTML For the sake of simplicity of this tutorial, only the HTML code is displayed below. For CSS used in the above screenshot, download the full source code at the end of this tutorial. Full Name * Email * Message * Send Message Ajax Form Submission Let’s work on the form submission using Ajax before we add the reCAPTCHA, for which we need the jQuery library. Load it using a CDN. Paste this line before the closing body tag in your HTML. We need to make the Ajax request on form submission. With this code, if you hit “Submit”, you will get a 404 error displayed because contact.php doesn’t exist yet. Let’s do that next. PHP Create contact.php. On the server side,  » Read More

Like to keep reading?

This article first appeared on If you'd like to keep reading, follow the white rabbit.

View Full Article

Leave a Reply