I am trying to implement Google\'s reCaptcha v.2.0 but i am getting null in g-recaptcha-response due to this reCaptcha is not working properly and I am always g
I'm not sure how you're submitting the form without an actual submit button, but I've copy/pasted your code and it works for me. I did change the error arrays into echo to display the else
messages.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form action="" method="POST">
<div class="g-recaptcha" style="margin-left: 230px; margin-top: 40px;" data-sitekey="Your-Public-Site-Key"></div>
<input type="submit" name="submit" value="Post comment">
</form>
</body>
</html>
<?php
if( isset($_POST['submit']) ) {
if( isset($_POST['g-recaptcha-response']) && !empty( $_POST['g-recaptcha-response'] ) ) {
//your site secret key
$secret = 'Your-Private-Site-Key';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success) {
// My All Logic Here
echo 'Success Message';
}
else {
echo 'Robot verification failed, please try again.';
}
}
else {
echo 'Please click on the reCAPTCHA box.';
}
}
?>
I've run into the same issue. The strangest part is a client-side call to grecaptcha.getResponse()
returns to correct response. For some reason it's just not setting g-recaptcha-response.
So my workaround was to set a data-callback function to populate a hidden field with the response and use that server-side instead. The hidden input also helps with ease of client-side validation.
eg:
<div class="g-recaptcha" data-callback="captcha_onclick" data-sitekey="######"></div>
<input type="hidden" name="recaptcha" id="recaptchaValidator" />
javascript:
function captcha_onclick() {
document.getElementById('recaptchaValidator').value = grecaptcha.getResponse();
}
server-side:
if(!empty($_POST['recaptcha'])) {
$captcha = $_POST['recaptcha'];
...
}