Google has launched a new and enhanced version of recaptcha called Google reCAPTCHA v3. It gives more security against the spam bot or abuse in your web forms. Google reCAPTCHA v3 works on the basis of spam score which means that the reCAPTCHA v3 API returns the spam score of each request given by the user activity.
In my previous tutorial, we have seen how to integrate Google reCAPTCHA v2 in PHP with an example. In this article also, I have used a simple contact form to demonstrate the integration of Google reCAPTCHA.
Do you want to create a simple contact form in PHP and HTML? I have also created a tutorial with a live demo to create simple Contact Form in PHP, Mysql and Ajax with Javascript Validation
This reCAPTCHA v3 is very easy to use compare to Google reCAPTCHA v2 because the user doesn't need to click on the checkbox which is in the Google reCAPTCHA v2. It just calculates the spam score based on the input data and user's activity and decides whether it is a spam activity or not.
In this tutorial, we will see to add Google reCAPTCHA v3 in PHP with the help of a contact form. If you have any contact form or any other form on your website and you are worried about the spam attack, then you are at the right place. We advise you to read this tutorial till the end and you will get clear knowledge to protect your forms from spambot attack.
Here, you can see the Google recaptcha v3 demo and I have created a working code so that you can easily download Google recaptcha v3 code and add it to your project or application.
You can read: AngularJS Tutorial RESTful JSON Parsing
The newer version of Google reCAPTCHA v3 gains more attention from developers because it reduces one extra click in your HTML forms. This reCAPTCHA v3 will not show any kind of captcha in your HTML forms. This means that it is invisible and it will not appear in your frontend forms on the web page, you can just see it at the right bottom corner of the page.
The Google reCAPTCHA v3 returns the spam score on each request without any interaction for the end-user. As Google reCAPTCHA v3 is invisible and does not interrupt any user interaction so we can call it anywhere in the website and user interaction, but it is best where we are capturing any input from the users.
We will follow the below steps to use Google reCAPTCHA V3 in PHP Contact form
You can also read: A Complete guide to Track Individual Logged in Users Using Google Analytics
First of all, we need to generate the Google reCAPTCHA Site key and Secret Key from Google reCAPTCHA official website. We have created a detailed tutorial on How to generate Google reCAPTCHA Site key and Secret Key. You can follow the simple steps from this tutorial and generate the site and secret key.
Now we assume that you have generated Google reCAPTCHA Site and Secret Key. You need to keep it for further use.
Here we have created a simple contact form in HTML and bootstrap to demonstrate the Google reCAPTCHA. we include a js file for calling Google reCAPTCHA API in HTML form.
<script async src="https://www.google.com/recaptcha/api.js?render=<YOUR_SITE_KEY>"></script>
Here, we need to change <YOUR_SITE_KEY>
with your generated site key. Also, we use recaptcha_response
as a hidden field and we will replace the value of this input filed using javascript call on runtime. So the Google reCAPTCHA API generates a unique key and stores the value in this input field. We will use this value in PHP file to validate the input value and calculate the spam score.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Google reCAPTCH V3 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script async src="https://www.google.com/recaptcha/api.js?render=<YOUR_SITE_KEY>"></script>
<style>
body{background-color:#f4f8fa;}
</style>
</head>
<body>
<div class="container col-sm-5" style="background-color:#ffffff; padding:25px; border: 1px solid #d9d8d8;">
<h1 style="font-size: 21px; font-weight: bold;">Demo of Integrate Google reCAPTCHA V3 in PHP</h1>
<form action="" method="post">
<div id="alert_message"></div>
<div class="form-group">
<label for="pwd">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter your name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" placeholder="Enter your email" name="email" required>
</div>
<div class="form-group">
<label for="email">Comment:</label>
<textarea name="comment" class="form-control" id="comment" placeholder="Enter your comment" required></textarea>
</div>
<input type="hidden" name="recaptcha_response" value="" id="recaptchaResponse">
<input type="submit" name="submit" value="Submit" class="btn btn-success btn-lg" style="padding: 6px 46px; margin: 16px 0 0 0;">
<div style="font-size: 12px; padding-top: 12px; color: #808080;">Note: This form is protected by Google reCAPTCHA.</div>
</form>
</div>
</body>
</html>
The Javascript code
This javascript code used to generate the reCAPTCHA code and set the value in HTML form.
grecaptcha.ready(function () {
grecaptcha.execute('<YOUR_SITE_KEY>', { action: 'submit' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
Now we make a AJAX request to call the PHP file and pass all the value of the contact form using ajax. So all the data will get validate and we get the response based on the Google reCAPTCHA API valiadation and its spam score.
At this stage, You can read: Submit form without refreshing page with jquery and ajax
<script>
$('form').submit(function(event) {
event.preventDefault(); //Prevent the default form submission
grecaptcha.ready(function () {
grecaptcha.execute('<YOUR_SITE_KEY>', { action: 'submit' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
// Making the simple AJAX call to capture the data and submit
$.ajax({
url: 'submit_enquiry.php',
type: 'post',
data: $('form').serialize(),
dataType: 'json',
success: function(response){
var error = response.error;
var success = response.success;
if(error != "") {
$('#alert_message').html(error);
}
else {
$('#alert_message').html(success);
}
},
error: function(jqXhr, json, errorThrown){
var error = jqXhr.responseText;
$('#alert_message').html(error);
}
});
});
});
});
</script>
This PHP file receives all the data input from the contact form and passes it into the Google reCAPTCHA API. Here, you need to replace the <YOUR_SECRET_KEY>
with your generated secret key. Now we call the reCAPTCHA API and pass these values into it to generate the spam score.
Once you call the API, you will receive the output like below:
{ "success": true, "challenge_ts": "2020-11-06T15:31:26Z", "hostname": "localhost", "score": 0.9, "action": "submit" }
Now you can process your application flow or capture the contact form data into a database or send a mail with this data to the system admin.
<?php
if(isset($_POST['name']) && $_POST['name']!="" && isset($_POST['email']) && $_POST['email']!="")
{
// This is Google API url where we pass the API secret key to validate the user request.
$google_recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret_key = '<YOUR_SECRET_KEY>'; // Add your generated Secret key
$set_recaptcha_response = $_POST['recaptcha_response'];
// Make the request and capture the response by making below request.
$get_recaptcha_response = file_get_contents($google_recaptcha_url . '?secret=' . $recaptcha_secret_key . '&response=' . $set_recaptcha_response);
print( $get_recaptcha_response);
$get_recaptcha_response = json_decode($get_recaptcha_response);
$success_msg="";
$err_msg="";
// Set the Google recaptcha spam score here and based the score, take your action
if ($get_recaptcha_response->success == true && $get_recaptcha_response->score >= 0.5 && $get_recaptcha_response->action == 'submit') {
$success_msg = "Your message has been sent successfully.";
} else {
$err_msg = "Something went wrong. Please try again after sometime.";
}
} else {
$err_msg = "Please enter the required fields in this form";
}
// Get the response and pass it into your ajax as a response.
$return_msg = array(
'error' => $err_msg,
'success' => $success_msg
);
echo json_encode($return_msg);
?>
Now we explain each step in detail to add Google reCAPTCHA V3 in PHP Contact form. I personally advise this reCAPTCHA to use your web forms or in your application to prevent the spam. If you find any difficulties to integrate it, feel to contact me, I will guide you to add it to your project.
Here are few FAQs about adding Google reCAPTCHA v3 in your PHP web application. These questions may arise at the time of Google reCAPTCHA v3 integration in any web application.
As we know that Google reCAPTCHA v3 API returns the captcha score ranging from 0 to 1. Practically, we can't increase or decrease this reCAPTCHA score as per our requirement. This reCAPTCHA score is completely based on your website behavior and user actions. Google's algorithm or their machine learning just learn your website traffic and based on your website traffic, it produces the reCAPTCHA score.
You will experience different reCAPTCHA scores in different locations or in different servers. The 0.5 score is a moderate score and you can go ahead with this score.
My Experience: When I login into any Google account like Gmail then the score which I received is 0.9. So I feel that Google links this score with their services. At the same time, when I test it in Incognito, then I see the score is 0.4. You can also have a try to increase your Google reCAPTCHA v3 score by logging into any Google services.