Skip to main content

Integrate Google No Captcha Recaptcha in PHP Form

Captcha is one of the best ways to protect any form spammers. Captcha helps websites to distinguish between machine and humans. Usually, captcha comes with a very an image with has some text written. The user needs to provide enter the text written on the image in any input field & the field get validate on the server. The text written on the image is little difficult to read and in the random pattern so that machines can not read. Although this is a good way to verify the human, but it is little frustrating user experience. To overcome with the frustrating experience Google has introduced No Captcha reCaptcha. In this post, we will explore on How to integrate Google no Captcha reCaptcha in PHP.
Before proceeding further let us explore what is “Google No Captcha reCaptcha” and a little history of google reCaptcha.

Google no captcha reCAPTCHA and its history

Google reCaptcha is a free service provided by Google for the bot or spam protection. Google reCaptcha provides a very advanced CAPTCHA to protect websites from any abusive activity.  You can use Google reCaptcha API and integrate into your website to protect your any specific page so that no any auto bot can do any activity.

Initially, Google reCaptcha was providing a text best CAPTCHA where the user will see a distorted no-pattern text written Image. The user needs to read the text and enter in the CAPTCHA textbox.
Google reCaptcha
Above is old Google reCAPTCHA. If you think as user experience perspective it is a little bit of frustrating user experience because the user needs to read some touch to read characters and type in the input box.

Considering the user experience Google launches noCAPTCHA reCaptcha, where the user does not need to input some touch reading character in the input box. Google noCaptcha reCaptcha is tough for bots but easy for humans. Below is a glimpse of noCaptcha reCaptcha
noCaptcha reCaptchaYou may refer to below Google webmaster video to learn more about reCaptcha

Hope you have a clear understanding about the purpose of noCaptcha. Now it’s time to integrate into your form using PHP.

If you are a beginner in PHP and want to learn how to code form with PHP, you may refer to PHP Form Handling Tutorial.

How Integrate Google No Captcha Recaptcha In PHP

Following are the steps we need to perform to integrate noCaptcha reCaptcha.

  1. Get noCAPTCHA reCaptcha API credentials.
  2. Integrate Google noCaptcha reCaptcha in your HTML form.
  3. Do the server side validation.

1. Get noCaptcha reCaptcha API credentials: Please go to Google reCaptcha Page and click on “Get reCaptcha” button from top right corner. Or you can also directly go to reCaptcha API key Manager. If you are not logged in then it will first ask you to login on your google account.
To get the reCaptcha API detail you need to follow a very small form with domin name of website with a label in following form:
noCaptcha API formFor this post I have generated separate keys. I have just entered test in label and localhost in domain. After clicking on “Register” button I got API key with some brief of integration.
Keys are below:
noCaptcha API Key
2. Integrate reCaptcha in your HTML Form: There are two way to integrate in the form. One is automatic way or easy wayother is explicit rendering or customize way.
Easy Way: To integrate google noCaptcha recaptcha in your HTML form first need to include the a JavaScript file in <head> tag of HTML page, I mean before </head> tag.
<script src='https://www.google.com/recaptcha/api.js></script>
Above code will render in english language. For tother language you can add language code as parameter in query string. For example for french it is hl=fr:
<script src='https://www.google.com/recaptcha/api.js?hl=fr'></script>

For all language code list visit Google Documentation

Now in your form where you want to add the noCaptcha recaptcha add following line of HTML:
<div class="g-recaptcha" data-sitekey="6LdeIh4TAAAAAGD2LZPyGGaoq4fjBntkfS9iYVRz"></div>

parameter sitekey is site key provide by Google.
Here is the complete code for small HTML form:
<html>
<head>
<title>How to integrate noCaptcha reCaptcha in PHP</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form method="post" action="easy.php">
<label for="input1">First Name</label>
<input type="text" name="input1"></br>
<label for="input2">Last Name</label>
<input type="text" name="input2"></br>
<label for="input3">Email</label>
<input type="text" name="input3"></br>
<div class="g-recaptcha" data-sitekey="6LdeIh4TAAAAAGD2LZPyGGaoq4fjBntkfS9iYVRz"></div>
<input type="submit" name="input1"></br>
</form>
</body>
</html>

And the above code will generate below page:Easy noCaptcha FormWe will discuss the explicit or custom way in the last part of the tutorial.  Let us first explore how to validate if user has verified that he is not robot.

3. Do the server side validation: To to the server side validation or verifying response using PHP first need to include the reCaptcha PHP Library  from github and place it in the folder.
Now add the following line in the top of your PHP code:
<?php
include 'recaptchalib.php';
$secretKey = '6LdeIh4TAAAAAFK7axxMJSVfEogUrc2P0haCOfn2';
$response = false;
$err_message = '';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(!empty($_POST['g-recaptcha-response'])){
$objRecaptcha = new ReCaptcha($secretKey);
$response = $objRecaptcha->verifyResponse($_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response']);
}
if(isset($response->success) && 1 == $response->success){
//Human is detected you can write script to perform actual action
}
else{
$err_message = 'You are not human';
}
}
?>

So in above code highlighted part is verifying the the response. Below is the code:
$objRecaptcha = new ReCaptcha($secretKey);
$response = $objRecaptcha->verifyResponse($_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response']);

Now the complete PHP Code is following for the easy way to integrate noCaptcha reCaptcha:

<?php
include 'recaptchalib.php';
$secretKey = '6LdeIh4TAAAAAFK7axxMJSVfEogUrc2P0haCOfn2';
$response = false;
$err_message = '';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(!empty($_POST['g-recaptcha-response'])){
$objRecaptcha = new ReCaptcha($secretKey);
$response = $objRecaptcha->verifyResponse($_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response']);
print_r($response);
}
if(isset($response->success) && 1 == $response->success){
//Human is detected you can write script to perform actual action
}
else{
$err_message = 'You are not human';
}
}
?>
<html>
<head>
<title>How to integrate noCaptcha reCaptcha in PHP</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php echo $err_message; ?>
<form method="post" action="easy.php">
<label for="input1">First Name</label>
<input type="text" name="input1"></br>
<label for="input2">Last Name</label>
<input type="text" name="input2"></br>
<label for="input3">Email</label>
<input type="text" name="input3"></br>
<div class="g-recaptcha" data-sitekey="6LdeIh4TAAAAAGD2LZPyGGaoq4fjBntkfS9iYVRz"></div>
<input type="submit" name="input1"></br>
</form>
</body>
</html>

In above example or way of implementation the Javascript will be added in header and will block rendering of the page. You can also integrate the Google noCaptcha reCaptcha without blocking the rendering.

Explicit rendering of noCaptcha reCaptcha

For explicit rendering we need to perform the following steps:

  1. Add JavaScript just before closing the body tag i.e. </body>
  2. Add parameter async defer in <script> tag
  3. Add parameter with onload=explict and onload call back method. Onload callback will executed once the script will be loaded.
  4. Write the code to add render google reCaptcha inside the onload callback.

By following the above approach let us modify our existing form.
Please add the following JavaScript just before closing the body:
<script src="https://www.google.com/recaptcha/api.js?onload=drawRecaptcha&render=explicit" async defer ></script>

Now you need to write a JavaScript function drawRecaptcha function on your page and in the function you can write below function to draw recaptcha:

grecaptcha.render(document.getElementById('recaptcha_explicit'), {
'sitekey' : '6LdeIh4TAAAAAGD2LZPyGGaoq4fjBntkfS9iYVRz',
'callback' : verifyCallback,
'theme' : 'light'
});

Now create a div with ID recaptcha_explicit in your form. Also you can have callback verifyCallback function when captcha is verified, but the Parameter is option.

Below is the complete code of explicit rendering:

<?php
include 'recaptchalib.php';
$secretKey = '6LdeIh4TAAAAAFK7axxMJSVfEogUrc2P0haCOfn2';
$response = false;
$err_message = '';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(!empty($_POST['g-recaptcha-response'])){
$objRecaptcha = new ReCaptcha($secretKey);
$response = $objRecaptcha->verifyResponse($_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response']);
print_r($response);
}
if(isset($response->success) && 1 == $response->success){
//Human is detected you can write script to perform actual action
}
else{
$err_message = 'You are not human';
}
}
?>
<html>
<head>
<title>How to integrate noCaptcha reCaptcha in PHP</title>
</head>
<body>
<?php echo $err_message; ?>
<form method="post" action="easy.php">
<label for="input1">First Name</label>
<input type="text" name="input1"></br>
<label for="input2">Last Name</label>
<input type="text" name="input2"></br>
<label for="input3">Email</label>
<input type="text" name="input3"></br>
<div id="recaptcha_explicit"></div>
<input type="submit" name="input1"></br>
</form>
<script>
var noCaptchaWidget;
function verifyCallback(response){
alert('recaptcha has been varified');
}
function drawRecaptcha(){
noCaptchaWidget = grecaptcha.render(document.getElementById('recaptcha_explicit'), {
'sitekey' : '6LdeIh4TAAAAAGD2LZPyGGaoq4fjBntkfS9iYVRz',
'callback' : verifyCallback,
'theme' : 'light'
});
}
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=drawRecaptcha&render=explicit" async defer ></script>
</body>
</html>

Download Code Used in this Post.

Note: The API key used in the example has been deleted. Please create your own API key.

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

3 thoughts on “Integrate Google No Captcha Recaptcha in PHP Form

Leave a Reply

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

shares