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);
}


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');


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.

Tagged: PHP Recaptcha
You can connect with me on Twitter or Linkedin.
Latest on My Blog
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Laravel High CPU Usage Because of File-based Session Storage
Laravel High CPU Usage Because of File-based Session Storage
Image for Resizing Droplets: A Personal Experience
Resizing Droplets: A Personal Experience
Image for Moving our CDN (10+ GB images) to a new server
Moving our CDN (10+ GB images) to a new server
Image for Disqus, the dark commenting system
Disqus, the dark commenting system
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Related Articles
1361