Using Google reCaptcha to authenticate user login on login form

| By Webner

Google reCaptcha is a free service API provided by Google to protect your site from unauthorized access, abuses and spam. The API uses advanced risk analysis technique to distinguish among a human being and a bot. The reCaptcha API comes in the form of a widget and it can be applied easily on any website.



How to use the reCaptcha widget:

Before using the widget on the website, the website owner needs to register his site at and sign up to get reCaptcha API key pair. The key pair includes two keys. One is the site key and another is the secret key.
The site key is required to display the widget on the web page whereas the secret key is used to authenticate the user using the site key and the reCaptcha response submitted by user. The secret key authorizes the communication between the website and the Google reCaptcha server, hence, it must be kept as a secret.

Applying reCaptcha on registration form:

Include the following script on the login web page as:

<script src="" async defer></script>

This will include google reCaptcha API’s javascript library which is required to display the widget on the web page.

Use below HTML code to add the widget:

<form method="POST" id =”loginForm” action=”login.php”>
    Email Id: <input name="email" value="" type="email"  />

Password: <input name="password" value="" type="password"  />
    <!--Add below line to display the reCaptcha widget-->

<div class="g-recaptcha" data-sitekey="<Your Site Key>"></div>
 <input name="login" value="Login"  type="submit">

The HTML code will display the widget on your login page just like above screenshot.

PHP code to get the reCaptcha response and authorize the user:


//verify if user has filled the captcha correctly

if(isset($this->request->data['g-recaptcha-response']) && !empty ($this->request-> data['g-recaptcha-response']))


$secret = “<your Secret key>”;

//get verify response data from reCaptcha server

$verifyResponse = file_get_contents(''.$secret.'&response='.$this->request->data['g-recaptcha-response']);

$responseData = json_decode($verifyResponse);


//reCaptcha API has validated the user as a human being. You can continue with validating user’s credentials here.



// show error message if response from the reCaptcha server is not ‘Success’

$error = 'Robot verification failed, please try again.';

echo $error;




//show error message if user has not clicked on reCaptcha box

$error = 'Robot verification is required to logged into the system. Please click on the reCaptcha box.';

echo $error;



When clicked on checkbox having label “I’m not a robot”, the reCaptcha widget on login form will ask the user to solve a simple puzzle as shown below.

After solving the reCaptcha correctly, Google API authenticates the presence of human being or a bot.

Leave a Reply

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