我正在尝试实施Google的reCaptcha v.2.0,但我在 g-recaptcha-response 中变为空,因为此reCaptcha无法正常工作,我总是收到的错误请点击reCAPTCHA框。即使我成功提交了Captcha。我var_dump
$_POST['g-recaptcha-response']
我正在null
。请帮我。以下是我的代码。
HTML
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<form action="" method="POST">
<div class="g-recaptcha" style="margin-left: 230px; margin-top: 40px;" data-sitekey="MySiteKey"></div>
</form>
PHP
if (isset($_POST['submit'])) {
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
//your site secret key
$secret = 'My Site Secret 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
} else {
$error[] = 'Robot verification failed, please try again.';
}
} else {
$error[] = 'Please click on the reCAPTCHA box.';
}
}
我总是收到错误请点击reCAPTCHA框。成功提交。请帮我。提前谢谢。
注意: - 表单之间没有使用表标记。
答案 0 :(得分:0)
我不确定您如何在没有实际提交按钮的情况下提交表单,但我已复制/粘贴您的代码,这对我有用。我确实将错误数组更改为echo以显示else
消息。
<!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.';
}
}
?>
答案 1 :(得分:0)
我遇到了同样的问题。最奇怪的部分是客户端调用grecaptcha.getResponse()
返回正确的响应。出于某种原因,它只是没有设置 g-recaptcha-response 。
所以我的解决方法是设置一个数据回调函数,用响应填充隐藏字段,然后使用服务器端。隐藏的输入也有助于方便客户端验证
例如:
<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();
}
的服务器端:
if(!empty($_POST['recaptcha'])) {
$captcha = $_POST['recaptcha'];
...
}