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.

	<script src=''></script>

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

	<title>Recaptcha Ajax</title>
	<script src=''></script>
	<div class="g-recaptcha" data-sitekey="yoursitekey"></div>
	<button onclick="sendAjaxRequest()">Submit</button>

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


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

	var response = grecaptcha.getResponse();

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

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


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.

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('', false, $context);
if (!$serverResponse) {
	exit('Failed to validate Recaptcha');
$result = json_decode($serverResponse);
if (!$result -> success) {
	exit('Invalid Recaptcha');
exit('Recaptcha Validated');


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
If you are interested in writing for Hyvor Developer, please let us know via email: [email protected]
Latest on Hyvor Developer
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
Image for Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image for PHP Contact Form - The Email Method
PHP Contact Form - The Email Method
Related Articles