Hyvor Developer LogoHYVOR DEVELOPER
Subscribe
Google Recaptcha with AJAX and PHP
php
May 1, 2018 8 mins 327

Validate Google Recaptcha with AJAX and PHP

For ease, I have divided this article into 4 topics

Creating a Recaptcha Account

Almost every internet user has a Google account. I assume that you have one too. If you don't have one, first, create a new google account. Then, visit google recaptcha, click GET RECAPTCHA button (the button in the top right corner in below image) and sign in with your Google account.

Google Recaptcha main page

In the form, add any label you like. Then, select reCAPTCHA v2 and add your domains. Here, you can even add a fake domain which you use in your localhost and it will function very well.

form to fill in when creating a recaptcha account for a website

Next, find your site key and secret key.

form to fill in when creating a recaptcha account for site

Adding Recaptcha to Your Site

First, you should add google recaptcha's external javascript file to your website. For that, add following code to your webpage that you need recaptcha to be. Google strongly recommend you to add the code inside <head> tag.


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


Then, paste this code wherever you want the reCAPTCHA widget to appear. You should replace the value of data-sitekey attribute with your site key


<div class="g-recaptcha" data-sitekey="6LcFi1YUAAAAABNVmcplInefsjo8dTHnuDRAgvqUvUh"></div>


Writing the Client-Side Code

Here's the full html code of index.html


<html>
<head>
	<title>Recaptcha Ajax</title>
	<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
	<div class="g-recaptcha" data-sitekey="yoursitekey"></div>
	<button onclick="sendAjaxRequest()">Submit</button>

	<script type="text/javascript">
		// your javascript here
	</script>

</body>
</html>


The JS code will be like following. The sendAjaxRequset() function is called when the button in the HTML page is clicked.


function sendAjaxRequest() {
	if (grecaptcha === undefined) {
		alert('Recaptcha not defined'); 
		return; 
	}

	var response = grecaptcha.getResponse();

	if (!response) {
		alert('Coud not get recaptcha response'); 
		return; 
	}

	var ajax = new XMLHttpRequest();
	ajax.onreadystatechange = function() {
		if (this.readyState === 4) {
			if (this.status === 200) {
				alert(this.responseText);
			}
		}
	}
	ajax.open('POST', 'validate-recaptcha.php', true);
	ajax.send('recaptcha=' + response);
}



function sendAjaxRequest() {
	if (grecaptcha === undefined) {
		alert('Recaptcha not defined'); 
		return; 
	}

	var response = grecaptcha.getResponse();

	if (!response) {
		alert('Coud not get recaptcha response'); 
		return; 
	}

	$.ajax({
	   url: 'validate-recaptcha.php',
	   success: function(result) {
	     	alert(result);
	   },
	   type: 'POST',
	   data: {
	   	recaptcha: response
	   }
	});

}


Explained...

grecaptcha is the global object defined by recaptcha as the handler. In the sendAjaxRequest() function, if grecaptcha object is not loaded, it will alert an error message and return from the function. Next, we get the response and do a simple validation on it. It will alert an error message if the response is empty. Next, we send a POST Ajax request to validate-recaptcha.php with the recaptcha response.

Validating Recaptcha with PHP

In this step, we will create validate-recaptcha.php to validate our recaptcha response.


<?php
if (empty($_POST['recaptcha'])) {
	exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(
 	array (
 		'response' => $response,
 		'secret' => 'yoursecretkey',
 		'remoteip' => $_SERVER['REMOTE_ADDR']
 	)
);
$opts = array('http' => 
	array (
		'method' => 'POST',
		'header' => 'application/x-www-form-urlencoded',
		'content' => $post
	)
);
$context = stream_context_create($opts);
$serverResponse = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
	exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
	exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');


  • First, we check whether the recaptcha POST variable is set.
  • Next, we save the recaptcha response in $response.
  • Next, we create a http query with http_build_query() function.
  • This includes the response, secret key of your site (Mind to change this with your secret key) and the IP address of the remote user.
  • Then, we create the steam, send the request to the server and save the response in $serverResponse variable.
  • This response is JSON encoded. So, we use json_decode() function to decode it. Then, we save the result in $result variable. If $result -> success is true, recaptcha is true.
Conclusion

That's all. Not so hard right? If you get any problem in creating your own function, let me know by commenting below. I'm here to help you always. I hope you enjoyed the article. Thank you for reading.

Author SupunKavinda