[英]How to pass Google reCAPTCHA v2 response code to server side PHP page using AJAX-jQuery
表单未使用AJAX-jQuery提交,因此未在服务器端PHP页面上获得响应密钥。
表格页
这部分非常简单,如下所示。
<script src='https://www.google.com/recaptcha/api.js'></script>
<form name="frm_add" id="frm_add" novalidate>
<div class="control-group form-group">
<div class="controls input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input name="name" id="name" class="form-control" type="text" value="">
</div>
<p class="help-block"></p>
</div>
<div class="g-recaptcha" data-sitekey="MY-SITE-KEY"></div>
<div id="success"></div>
<button type="submit" value="Submit">Submit</button>
</form>
jQuery / AJAX页面
如果删除g-recaptcha-response: grecaptcha.getResponse(),
此JS页面中的代码将使用jQuery-AJAX提交页面,而不会出现任何问题,并且一切顺利。 但是,当我将下面的示例代码中编写的代码放在上面时,则表单没有使用POST方法提交,因此我猜想这段代码有问题。 我在互联网上搜索并阅读了许多教程和代码,但无法解决此问题。
$(function() {
$("#frm_add input,#frm_add textarea ,#frm_add select").jqBootstrapValidation( {
.
.
$.ajax({
url: "./user/offer_p.php",
type: "POST",
data: {
g-recaptcha-response: grecaptcha.getResponse(),
name: name
},
cache: false,
.
.
}
}
服务器端PHP页面
如果我直接使用POST方法(不使用jQuery-AJAX POST方法)提交表单,则以下代码可以正常工作。
$ipaddress = $_SERVER['REMOTE_ADDR'];
$secretkey = "MY-SECRET-KEY";
$responsekey = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$post_data = http_build_query(
array (
'secret' => $secretkey,
'response' => $responsekey,
'remoteip' => $ipaddress
)
);
$options=array (
'http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($options);
$result_json = file_get_contents($url, false, $context);
$resulting = json_decode($result_json, true);
if($resulting["success"] != 1)
{
$response['status']='ERR';
$response['message']= "Invalide Captcha!";
echo json_encode($response);
return;
}
服务器端PHP页面
$response = file_get_contents ( "https://www.google.com/recaptcha/api/siteverify?secret=" . PRIVATE_CAPTCHA_KEY . "&response=" . $_POST ['g-recaptcha-response'] . "&remoteip=" . $_SERVER ['REMOTE_ADDR'] );
$responseData = json_decode ( $response );
if ($responseData->success) {
// TRUE
}else{
//False
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.