How to integrate google captcha with php?

Hi guys, today we are going to discuss how to integrate Google Captcha with our php website. As we all know that we are living in the world of technology. Also, it is very easy to hack someone’s website or to steal someone’s website data by running some scripts. So, to protect our website data from hackers or bots we use google’s Captcha or reCaptcha script.

A Captcha is a short term used for “Completely Automated Public Turing test to tell Computers and Humans Apart” is a type of challenge to judge that the computer user is Human or bot. It is very basic security for our website data and everyone is using this technology.

The logic of Captcha or reCaptcha is whenever the human uses the computer they have to click the Captcha and it will send the request to the google to verify the user. But when the Bot uses the computer the Captcha is not verified so that it will prevent the user to move forward or hack the data.

In this article, we will learn how to register our website to use the google’s Captcha or reCaptcha.

How to prevent our website from bots ( Short for ‘robots’ )

To prevent our website from these attacks, Google is providing a technique to protect our website. The technique that we will use to protect our website is captcha or reCaptcha. Captcha or reCaptcha is a technique generated or designed by system to protect the websites from bots.

What is bot?

Bot is a short term for “robots”. Bot is like a computer code that runs over the internet. Bots are of two types one runs automatically while another runs commands only when they receive some specific input.

Why we use Captcha or reCaptcha ?

We use Captcha or reCaptcha to verify whether the computer user is the robot or human. Also, if we are not verifying the computer user then it will be very harmful for us, may be we will loose our data. So, for that purpose we use Google Captcha or reCaptcha.

How Captcha or reCaptcha looks ?

Above is an example of Google reCaptcha.

Steps to integrate Google captcha with our php website:

Step 1: Register your domain to use captcha.

First of all, we have to register our website or domain for Google Captcha or reCaptcha. Below is the url to register for Google Captcha.

https://www.google.com/recaptcha/admin

Also, once you login into above url with your gmail id then you will get a form where you have to write your domain name, choose the type of Captcha and label on which page you will use the Captcha. Below is the screen after login to Google.

After this, click on register button you will get a page where your site key and secret key will be available. Also, below is the screen of site key and secret key.

After this, click on the save changes button your site and secret key for Captcha will be enabled or ready to use.

Site-key

Site key is used to add or show the widget for Captcha in your HTML page. Also, below is the example of site key.

Site Key = 8hvJHVBhjHfHJf657nkmBJjjvjh71d87hkad

Secret key

A secret key is used to communicate between your website and reCaptcha server. Also, below is the example of a secret key.

Secret Key  = 6hvjhJHhvbjhvjhDdfGsddgEvjhjvjh78687h_kjn

Step 2: Include script file for Google captcha.

You need to add Google Captcha javascript API into your HTML section before closing of the </head> tag as shown below.

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

In addition, if you are not including the above script tag in your HTML template. Then you will not be able to view the Captcha or reCaptcha widget on your HTML page.

Step 3: Include HTML section of Google reCaptcha widget.

We need to add a <div> tag to display the Google reCaptcha into our form. Also, below is the widget of Google reCaptcha.

<div class="g-recaptcha" data-sitekey="9LDDpf0eVtMZY6kdJnGhsYYY-5ksd-W"></div>

For that purpose, you need to create a form in which you want to add Google reCaptcha widget to verify that the computer user is human or bots. We have to add the Google reCaptcha widget just before the submit button as shown below.

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Google reCaptcha 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/3.3.7/css/bootstrap.min.css”>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js”></script>
<script src=”https://www.google.com/recaptcha/api.js” async defer></script>
</head>
<body>

<div class=”container”>
<?php

if(!empty($htmlContent))
{
echo $htmlContent;
}
else
{
echo “”;
}
?>
<h2>Registration form</h2>
<form action=”” method=”post”>
<div class=”form-group”>
<label for=”email”>Email:</label>
<input type=”email” class=”form-control” id=”email” placeholder=”Enter email” name=”email”>
</div>
<div class=”form-group”>
<label for=”pwd”>Password:</label>
<input type=”password” class=”form-control” id=”pwd” placeholder=”Enter password” name=”pwd”>
</div>
<div class=”form-group”>
<label for=”pwd”>Name:</label>
<input type=”text” class=”form-control” id=”name” placeholder=”Enter Name” name=”name”>
</div>
<div class=”g-recaptcha” data-sitekey=”6LfTPlUUAAAAAGSUt1_LqpJXQpatx7_BzTDcU9On”></div>
<input type=”submit” class=”btn btn-default” id=”submit” name=”submit” value=”Submit”/>
</form>
</div>

</body>
</html>

As we can see the above HTML code that includes the Javascript API and Google reCaptcha widget on the registration form.

Step 4: Validate PHP code.

We need to check that all fields are filled and reCaptcha is clicked by the computer user or not. So, for that purpose, we need to validate the form fields and reCaptcha. Also, below is the whole validation code.

<?php
error_reporting(0);
if (isset($_POST[‘submit’]) && !empty($_POST[‘submit’])) {
if (isset($_POST[‘g-recaptcha-response’]) && !empty($_POST[‘g-recaptcha-response’])) {
//Below is your secret key
$secret = ‘6LfTPlUUAAAAANgJTPa67hlDAXu4ppK2FgSbSOO6’;
//get verify response data
$captchaResponse = file_get_contents(‘https://www.google.com/recaptcha/api/siteverify?secret=’ . $secret . ‘&response=’ . $_POST[‘g-recaptcha-response’]);
$responseData = json_decode($captchaResponse );
if ($responseData->success) {
//Registration form submission code
$name = !empty($_POST[‘name’]) ? $_POST[‘name’] : ”;
$email = !empty($_POST[’email’]) ? $_POST[’email’] : ”;
$password = !empty($_POST[‘pwd’]) ? $_POST[‘pwd’] : ”;

$htmlContent = “
<h1>Registration details</h1>
<p><b>Name: </b>” . $name . “</p>
<p><b>Email: </b>” . $email . “</p>
<p><b>Message: </b>” . $password . “</p>
“;
} else {
$errMsg = ‘Captcha verification failed, please try again.’;
echo “<script>alert(‘” . $errMsg . “‘);</script>”;
}
} else {
$errMsg = ‘Please click on the reCAPTCHA box.’;
echo “<script>alert(‘” . $errMsg . “‘);</script>”;
}
} else {
$errMsg = ”;
echo “<script>alert(‘Please fill data’);</script>”;
}
?>

In above code first, we check that submit button is pressed or not. If it is not pressed then it will alert a message i.e ‘Please fill the fields’. Then we will check that reCaptcha is clicked or not. After checking all the validation we will hit an API to verify that captcha and if the response is true or successful then we will show the user details otherwise it will alert a message that Captcha verification failed.

In addition, below is the combined code and save it as captcha.php.

<?php
error_reporting(0);
if (isset($_POST[‘submit’]) && !empty($_POST[‘submit’])) {
if (isset($_POST[‘g-recaptcha-response’]) && !empty($_POST[‘g-recaptcha-response’])) {
//Below is your secret key
$secret = ‘6LfTPlUUAAAAANgJTPa67hlDAXu4ppK2FgSbSOO6’;
//get verify response data
$captchaResponse = file_get_contents(‘https://www.google.com/recaptcha/api/siteverify?secret=’ . $secret . ‘&response=’ . $_POST[‘g-recaptcha-response’]);
$responseData = json_decode($captchaResponse );
if ($responseData->success) {
//Registration form submission code
$name = !empty($_POST[‘name’]) ? $_POST[‘name’] : ”;
$email = !empty($_POST[’email’]) ? $_POST[’email’] : ”;
$password = !empty($_POST[‘pwd’]) ? $_POST[‘pwd’] : ”;

$htmlContent = “
<h1>Registration details</h1>
<p><b>Name: </b>” . $name . “</p>
<p><b>Email: </b>” . $email . “</p>
<p><b>Message: </b>” . $password . “</p>
“;
} else {
$errMsg = ‘Captcha verification failed, please try again.’;
echo “<script>alert(‘” . $errMsg . “‘);</script>”;
}
} else {
$errMsg = ‘Please click on the reCAPTCHA box.’;
echo “<script>alert(‘” . $errMsg . “‘);</script>”;
}
} else {
$errMsg = ”;
echo “<script>alert(‘Please fill data’);</script>”;
}
?>

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Google reCaptcha 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/3.3.7/css/bootstrap.min.css”>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js”></script>
<script src=”https://www.google.com/recaptcha/api.js” async defer></script>
</head>
<body>

<div class=”container”>
<?php
if (!empty($htmlContent)) {
echo $htmlContent;
} else {
echo “”;
}
?>
<h2>Registration form</h2>
<form action=”” method=”post”>
<div class=”form-group”>
<label for=”email”>Email:</label>
<input type=”email” class=”form-control” id=”email” placeholder=”Enter email” name=”email”>
</div>
<div class=”form-group”>
<label for=”pwd”>Password:</label>
<input type=”password” class=”form-control” id=”pwd” placeholder=”Enter password” name=”pwd”>
</div>
<div class=”form-group”>
<label for=”pwd”>Name:</label>
<input type=”text” class=”form-control” id=”name” placeholder=”Enter Name” name=”name”>
</div>
<div class=”g-recaptcha” data-sitekey=”6LfTPlUUAAAAAGSUt1_LqpJXQpatx7_BzTDcU9On”></div>
<input type=”submit” class=”btn btn-default” id=”submit” name=”submit” value=”Submit”/>
</form>
</div>

</body>
</html>

Conclusion

In this article, we have learned how to integrate Google Captcha or reCaptcha in any website’s registration form. Also, we have learned that how to register our website for using Google’s reCaptcha. If you have any query regarding this article, please comment in the comment section. Thank you!

3 thoughts on “How to integrate google captcha with php?”

  1. Pingback: URL

Leave a Comment