使用cURL从php验证Google的reCaptcha代码

时间:2017-01-26 20:12:15

标签: php curl recaptcha

我尝试使用cURL请求验证发送到我的服务器的reCaptcha代码。到目前为止,这是代码:

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;
    }
}

我得到的回复是null,它提供的错误有时为0,有时为空白。所以我在这里完全不知所措。如何编码才能正常工作?

我正在关注reCaptcha here的文档。

编辑:我已经尝试过发布here的解决方案,但它对我不起作用。

2 个答案:

答案 0 :(得分:2)

当我在相关问题中阅读时,我设法使用file_get_contents。因此,对于那些可能像我一样陷入困境的人,我会将我的解决方案作为答案发布。

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;
}

解决方案几乎逐字地从here中提取。

答案 1 :(得分:0)

有时您必须将其添加到php.ini中:

allow_url_fopen = 1 
allow_url_include = 1