Google reCAPTCHA v3 in PHP
Google has introduced reCAPTCHA v3 verification to prevent spamming and abusive terrific traffic on websites. In this tutorial, we’ll explain to you an easy way to integrate Google reCAPTCHA v3 in PHP.
Here, we will create a simple form to submit the name and email with validation of the reCAPTCHA v3 and store the information into the database. reCAPTCHA v3 doesn’t require the user friction.
Demo Example
Output - Google reCAPTCHA v3 in PHP - Clue Mediator
Steps to add Google reCAPTCHA v3
- Register your website and generate keys
- Create HTML form
- PHP code for server side integration
- Output
File Structure
-
php-recaptcha-v3
- index.php
- recaptcha-validate.php
1. Register your website and generate keys
First of all, you need to register your website on Google reCAPTCHA for that click here and login with a Google account. After logged in, you will see the Google form as shown below.
Generate reCAPTCHA Keys – Google reCAPTCHA v3 in PHP – Clue Mediator
Fill the information as mentioned in the above screenshot and click on the Submit button.
After successful registration, Google will provide you a SITE KEY and SECRET KEY which will be used to configure the form on the domains.
2. Create HTML form
Here, we will create a simple form with Google reCAPTCHA v3 that contains name and email to store in the database.
index.php
<title>Google reCAPTCHA v3 using PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?render=<YOUR_SITE_KEY>"></script>
<style>
body {
font-family: arial;
margin: 20px;
}
</style>
<div class="col-md-6">
<h4>Google reCAPTCHA v3 in PHP - <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h4>
<form id="myform" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" id="email" required>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
<p id="message" class="mt-3"></p>
</div>
<script>
$('#myform').submit(function (e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
// needs for recaptcha ready
grecaptcha.ready(function () {
// do request for recaptcha token
grecaptcha.execute('<YOUR_SITE_KEY>', { action: 'contact' }).then(function (token) {
// add token to form
$.post("recaptcha-validate.php", { name: name, email: email, token: token }, function (result) {
var data = JSON.parse(result);
$('#message').text(data.msg);
});
});;
});
});
</script>
In the above code, you need to update `<YOUR_SITE_KEY>` in two places (Script URL & JavaScript Code).
3. PHP code for server side integration
Let’s create a table named `user_data` in the database.
CREATE TABLE user_data (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL
)
Now, we will write a PHP code in the PHP file named `recaptcha-validate.php` to validate the reCAPTCHA and insert the data into the database.
recaptcha-validate.php
<!--?php
$name = $_POST['name'];
$email = $_POST['email'];
$token = $_POST['token'];<p-->
if(!$token){
echo '<h2>Please check the captcha form.</h2>';
exit;
}
$secretKey = "<your_secret_key>";
// post request to server
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => $secretKey, 'response' => $token);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($recaptcha_url, false, $context);
$responseKeys = json_decode($response,true);
if($responseKeys["success"]) {
// Database connection
$con = mysqli_connect("localhost", "root", "" , "demo") or die($con);
// Insert data into database
$sql = "INSERT INTO user_data (name, email) VALUES ('$name', '$email')";
mysqli_query($con,$sql);
$output['success'] = true;
$output['msg'] = "Your form has been successfully submitted.";
} else {
$output['success'] = false;
$output['msg'] = "You are robot!";
}
echo json_encode($output);
?>
</your_secret_key>
Don’t forget to update the `<YOUR_SECRET_KEY>` in the above code.
You will receive the following response from the Google reCAPTCHA API. Just print the `$responseKeys` variable in the above code to check the response.
Array
(
[success] => 1
[challenge_ts] => 2020-11-06T11:50:49Z
[hostname] => localhost
[score] => 0.9
[action] => contact
)
For more information about server side integration click here.
4. Output
Run the web page and check the output in the browser.
Note: Google reCAPTCHA v3 is invisible so you won’t see a captcha on your website.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂