Adding Google reCAPTCHA v3 to a PHP form with Ajax

To prevent spam and bots request, Google provides a service named as reCAPTCHA. reCAPTCHA is a free service provided by Google that protects your website from spam and abuse traffic and request. In this tutorial, I am going to share with you how to add Google reCAPTCHA v3 to a PHP form with Ajax?

In this example, I am submitting the PHP form with the help of Ajax and also implementing reCAPTCHA v3 at the time of form submission to prevent spam and bots request.

The reCAPTCHA v3 is completely different from the previous version of reCAPTCHA because there is no user interaction in v3 that’s why the user does not need to do anything for reCAPTCHA verification at the time of form submission.

In the previous tutorial, I shared how to implement Google reCAPTCHA v3 without Ajax?

How Google reCAPTCHA v3 works?

Before knowing the implementation of reCAPTCHA v3, we will see how it works on websites because an image is worth a thousand words! Let’s see the workflow.

Google reCAPTCHA v3 workflow
Google reCAPTCHA v3 workflow

Let’s have a look at this image that how reCAPTCHA works?

  1. At the first step, a user request for a webpage.
  2. The browser sends a request to the webserver for the requested webpage.
  3. The web server returns a webpage as a response to the browser which contains Google reCAPTCHA v3 code.
  4. The user fills the form and clicks on the submit button to submit the form. After that, the reCAPTCHA library will send a request to the Google server.
  5. Google server returns a token as a response. This token will be added in the form data and will be sent to the webserver for the next process.
  6. Now, form data will be sent to the webserver to store it on the database. With the form data, token will also send to the webserver.
  7. The web server receives the request which comes from the front-end and will send a request to the Google server with the help of a reCAPTCHA API. In this request, token and site key will be sent.
  8. Google server returns a response. In this response, score, success, action, hostname, etc. are available by which we can verify the human or robot.
  9. Now, the web server verifies the response one by one and it returns the result to the user that request sends by human or robots.

response

{
  "success": true|false,      // whether this request was a valid reCAPTCHA token for your site
  "score": number             // the score for this request (0.0 - 1.0)
  "action": string            // the action name for this request (important to verify)
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}

There are three main points to verify that the request has been sent by a human.

  • First, you need to check the value of success. If it is true then you need to check the next step otherwise you need to reject the request. The response success tells that the request was valid reCAPTCHA or not.
  • Score range from 0.0 to 1.0. The score greater than or equal to 0.5 represents the human request and less than 0.5 represents the robot’s request. You must have to verify the score.
  • The action was submitted at the time of the token generation. You will get the same action in response. You need to verify that your requested action is the same or not in response. If it same then the next verification process will be processed.
  • Challen_ts is the timestamp which represents the verification time of reCAPTCHA.
  • The hostname represents the web URL where reCAPTCHA verification done. You can also verify it for better results.

The main three points are success, score, and action which is helpful to prevent spam requests with the help of Google reCAPTCHA.

Register on reCAPTCHA for site key and secret key

To get site key (for client-side integration) and secret key (for server-side integration), you need to register on Google reCAPTCHA site. Follow the below steps and get a site key and secret key by registering on the reCAPTCHA website.

First, visit the reCAPTCHA official website by clicking on this link. Click here for the reCAPTCHA website.

Google reCAPTCHA v3 form
Google reCAPTCHA v3 form

Login with your Gmail account and Open register a new site form by clicking on the plus icon. In this form, there is the following field which you need to fill:

  1. Label: You can enter the label name according to your website name. For example, your website is a tutorials blog then you can enter tutorials blog in the label field. You can enter anything here according to your suitable website name.
  2. reCAPTCHA type: Select reCAPTCHA v3
  3. Domains: You need to enter your domain URL here on which you want to implement reCAPTCHA. If you are implementing on localhost then you need to enter two domains: localhost and 127.0.0.1. For the live domain, you need to enter only domain name and extension only. For example, your website URL is www.example.com then you need to enter example.com here.
  4. Accept the reCAPTCHA terms and services and finally submit the form.

Now, you will get a site key and secret key. With the help of the site key and secret key, you can implement Google reCAPTCHA on your website to prevent spam requests.

reCAPTCHA site key and secret key

Google reCAPTCHA v3 integration with example

In this example, we will create two PHP files. one is index.php and another one is recaptcha.php. In index.php, we will write code for front-end which means to design form and also we will implement reCAPTCHA client-side.

In the recaptcha.php file, we will write code to receive form data which was submitted by Ajax and also we will write code to execute server-side reCAPTCHA implementation code. Let’s integrate reCAPTCHA code one by one at both sides.

Client-side integration of reCAPTCHA

index.php

<!DOCTYPE html>
<html>
<head>
	<title>Google Recaptcha V3</title>
	<style type="text/css">
		body{
			margin-left: 20%;
		}
	</style>
</head>
<body>
	<div class="container">
		<h1>Google Recaptcha V3</h1>
		<form id="simple_form">
			<label>Name</label><br>
			<input type="text" name="name" id="name"><br><br>
			<label>Message</label><br>
			<textarea name="message" id="message"></textarea><br><br>
			<input type="submit" name="submit">
		</form>
	</div>

	<script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
	<script  src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
	<script type="text/javascript">
		$(document).on('submit', '#simple_form', function(e){
			e.preventDefault();
			grecaptcha.ready(function() {
			    grecaptcha.execute('put your site key here', {action: 'application_form'}).then(function(token) {

			    	let formData = {
			    		name : $('#name').val(),
			    		message : $('#message').val(),
			    		action: 'application_form',
			    		token: token
			    	};
			    	$.post('recaptcha.php', formData, function(response){
			    		alert(response);
			    	});
			    });
			});
		});

	</script>
</body>
</html>

Let’s understand the code snippets line by line.

First of all, a form has been designed with two fields (name and message) and a submit button to submit the form. After that, two external JavaScript file has been linked with the help of the script tag. One JavaScript is Google reCAPTCHA API and another one is the jQuery library which helps to write a simple code of form submission by Ajax.

In Google reCAPTCHA API, put your site key instead of “put your site key here” text which was got at the time of registration on Google reCAPTCHA.

Now, a line of code has been written to submit the form via Ajax and inside it e.preventDefault() has been written to prevent a submit button from submitting a form. When we submit a form via Ajax then we need to prevent form submission by HTML because of that process refresh the browser at the time of form submission but ajax provides facility to submit the form data to the backend without refresh the web browser. To know more about e.preventDefault() follow this tutorial: e.preventDefault() Tutorial

Next, the grecaptcha object calls the execute method to get a token from the Google server. The most important thing is that you need to pass the site key and action at the time of the token generation. You can get the site key from your reCAPTCHA account and you can pass a suitable action name according to your requirement. Here, I am passing the application_form value in action because I am creating a simple form.

After receiving a token from the Google server, we will send form data with token and action to the back end server to verify the reCAPTCHA response.

Server-side integration

recaptcha.php

<?php
$name = $_POST['name'];
$message = $_POST['message'];
$token = $_POST['token'];
$action = $_POST['action'];

$curlData = array(
	'secret'	=> 'put your secret key here',
	'response'	=> $token
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($ch);

$captchaResponse = json_decode($curlResponse, true);

if($captchaResponse['success'] == '1' 
	&& $captchaResponse['action'] == $action 
	&& $captchaResponse['score'] >= 0.5 
	&& $captchaResponse['hostname'] ==  $_SERVER['SERVER_NAME'])
{
	echo 'Form Submitted Successfully';
}
else{
	echo 'You are not a human';
}

On the server-side, we are receiving all values one by one such as name, message, token, and action. Then we are creating a simple array in which there are two indexes one for secret key and another one for a token. Indexes like secret and response.

Next, cURL is executed with the help of this URL https://www.google.com/recaptcha/api/siteverify and then it returns a JSON response. In the JSON response, we will get a score, success, access, hostname, etc.

Next, we are verifying response with an if condition and if the condition is true then it returns “Form submitted successfully” otherwise it returns “You are not a human“.

In the true section of the condition, you can perform your operation like data insertion in the database, update, deletion anything which you want to perform if the request sent by the user.

Conclusion

Google provides a better solution to prevent spam requests and abusive traffic on the website. Google updates their services always to give a better look and for better user experience.

In this tutorial, I shared with you how to implement Google reCAPTCHA v3 to a PHP form with the help of Ajax? I hope this tutorial will be very helpful to you.

2 thoughts on “Adding Google reCAPTCHA v3 to a PHP form with Ajax

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!
iganony