How to implement Google reCaptcha V2

Doing the basics

Go to https://www.google.com/recaptcha/about/ → Click on V3 Admin Console and register a new web site.

We need to fill out the form. remember to mark the I’m not a robot type of validation and enter the domains where going to place the reCaptcha V2

After that, we will have our Web key and Secret Key

Let’s do some coding

To do a successful implementation we need to add 3 fragments of code

1. Front-end code

<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
  1. We need to replace “your_site_key” with the site key given to us in our Google reCaptcha Console
  2. We need to replace “?” with your file.php of the action of your form

It should show as this on your webpage

2. Back-end Code validation

On your file.php of the action form, we need to do the validation of the successful I’m not a robot button.

For that, we need this library to help us with the validation

Create a file called recaptchalib.php and copy & paste the below code and place it in your project.

<?php
/**
* This is a PHP library that handles calling reCAPTCHA.
* - Documentation and latest version
* https://developers.google.com/recaptcha/docs/php
* - Get a reCAPTCHA API Key
* https://www.google.com/recaptcha/admin/create
* - Discussion group
* http://groups.google.com/group/recaptcha
*
*
@copyright Copyright (c) 2014, Google Inc.
*
@link http://www.google.com/recaptcha
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


/**
* A ReCaptchaResponse is returned from checkAnswer().
*/

class ReCaptchaResponse
{
public $success;
public $errorCodes;
}

class ReCaptcha
{
private static $_signupUrl = "https://www.google.com/recaptcha/admin";
private static $_siteVerifyUrl =
"https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_1.0";

/**
* Constructor.
*
*
@param string $secret shared secret between site and ReCAPTCHA server.
*/

function ReCaptcha($secret)
{
if ($secret == null || $secret == "") {
die("To use reCAPTCHA you must get an API key from <a href='"
.
self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
}
$this->_secret=$secret;
}

/**
* Encodes the given data into a query string format.
*
*
@param array $data array of string elements to be encoded.
*
*
@return string - encoded request.
*/

private function _encodeQS($data)
{
$req = "";
foreach ($data as $key => $value) {
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}

// Cut the last '&'
$req=substr($req, 0, strlen($req)-1);
return $req;
}

/**
* Submits an HTTP GET to a reCAPTCHA server.
*
*
@param string $path url path to recaptcha server.
*
@param array $data array of parameters to be sent.
*
*
@return array response
*/

private function _submitHTTPGet($path, $data)
{
$req = $this->_encodeQS($data);
$response = file_get_contents($path . $req);
return $response;
}

/**
* Calls the reCAPTCHA siteverify API to verify whether the user passes
* CAPTCHA test.
*
*
@param string $remoteIp IP address of end user.
*
@param string $response response string from recaptcha verification.
*
*
@return ReCaptchaResponse
*/

public function verifyResponse($remoteIp, $response)
{
// Discard empty solution submissions
if ($response == null || strlen($response) == 0) {
$recaptchaResponse = new ReCaptchaResponse();
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = 'missing-input';
return $recaptchaResponse;
}

$getResponse = $this->_submitHttpGet(
self::$_siteVerifyUrl,
array (
'secret' => $this->_secret,
'remoteip' => $remoteIp,
'v' => self::$_version,
'response' => $response
)
);
$answers = json_decode($getResponse, true);
$recaptchaResponse = new ReCaptchaResponse();

if (trim($answers ['success']) == true) {
$recaptchaResponse->success = true;
}
else {
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = $answers [error-codes];
}

return $recaptchaResponse;
}
}

?>

Now on your file.php, we place this code

require_once 'recaptchalib.php';

//Secret from Google captcha
$secret = '246L**************************f8BP';
//Object creation
$recapObj = new ReCaptcha($secret);

//Capturing the recaptcha response from the form POST
$g_recaptcha_response = $_POST['g-recaptcha-response'];
//validation of the Google captcha
$captcha_validation_response = $recapObj->verifyResponse('',$g_recaptcha_response);
$response = $captcha_validation_response->success;

if($response){

//your code here

}

3. Client side validation

Finally, we add some JavaScript validation for a better user experience on the front-end

  1. We Add tag id to our captcha
<div class="g-recaptcha" id="captchaV" data-sitekey="your_site_key"></div>

2. We add an OnSubmit to our form

<form action="file.php" onsubmit="return validationRecaptcha()" method="POST">

3. And our JavaScript that will add a red line if fail our Captcha

function validationRecaptcha() {
var response = grecaptcha.getResponse();
var captchaWidget = document.getElementById('captchaV');
if (response.length === 0) {
// reCAPTCHA not verified, add red border and prevent form submission
captchaWidget.style.border = '2px solid red';
return false;
} else {
// reCAPTCHA verified, remove red border and allow form submission
captchaWidget.style.border = '';
return true;
}
}




captcha google recaptcha v2