[英]Validate Google's reCaptcha code from php using cURL
I'm trying to validate the reCaptcha code sent to my server using a cURL request.我正在尝试使用 cURL 请求验证发送到我的服务器的 reCaptcha 代码。 So far, this is the code:
到目前为止,这是代码:
function verifyReCaptcha($conn,$recaptchaCode){
$curl = curl_init("https://www.google.com/recaptcha/api/siteverify");
$data = ["secret"=>"XXXXXX","response"=>$recaptchaCode];
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Accept: application/json'),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data));
$resp = curl_exec($curl);
curl_close($curl);
if ($resp == NULL){
echo "Error: ".curl_errno($curl);
} else {
echo $resp;
}
}
The response that I'm getting is null
, and the error it gives is sometimes 0
, sometimes blank.我得到的响应是
null
,它给出的错误有时是0
,有时是空白。 So I'm completely at a loss here.所以我在这里完全不知所措。 How should it be coded to work properly?
应该如何编码才能正常工作?
I'm following the documentation for reCaptcha here .我正在关注 reCaptcha这里的文档。
EDIT: I've already tried the solution posted here , but it does not work for me.编辑:我已经尝试过这里发布的解决方案,但它对我不起作用。
I managed to do it using file_get_contents
, as I read in a related question.正如我在相关问题中所读到的那样,我设法使用
file_get_contents
做到了这一点。 So I'll post my solution as an answer, for anyone who may be stranded like I was.因此,对于可能像我一样陷入困境的任何人,我都会发布我的解决方案作为答案。
function verifyReCaptcha($recaptchaCode){
$postdata = http_build_query(["secret"=>"XXXXXX","response"=>$recaptchaCode]);
$opts = ['http' =>
[
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
]
];
$context = stream_context_create($opts);
$result = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$check = json_decode($result);
return $check->success;
}
The solution is extracted almost verbatim from here .解决方案几乎是从这里逐字提取的。
Sometimes you have to add this to your php.ini:有时您必须将其添加到 php.ini 中:
allow_url_fopen = 1
allow_url_include = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.