Google Recaptcha with AJAX and PHP


#1

Hello, dear 000webhost users!

I can see you are growing day by day. 000webhost now hosts a bunch of superbly designed websites. I hope this article would help you to increase your website’s security with Google Recaptcha.

On the assumption that, you have a Google Recaptcha account, I will continue the tutorial. If you don’t have one, please follow the link at the end of this article.

Adding Google Recaptcha to your website

Add following code inside <head> tag to initiate Recaptcha in your site.

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

Then, add following code in the place where you need the Recaptcha widget to appear.

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

Mind replacing data-sitekey with your site key

Sending the Ajax Request on Button Click

This is the HTML code…

 <body>
    <div class="g-recaptcha" data-sitekey="yoursitekey"></div>
    <button onclick="sendAjaxRequest()">Submit</button>

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

</body>

This is the javascript code…

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);
}
If you are using jQuery
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
	   }
	});

}

Validating the Recaptcha response with PHP

validate-recaptcha.php

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

If the response of validate-recaptcha.php is “Recaptcha Validated”, everything went fine. Otherwise, something was wrong. Maybe it was a bot :smile:

For the full tutorial, following link
Validate Google Recaptcha with AJAX and PHP

Thank you for reading!

Supun Kavinda,
Moderator,
000webhost.