Recaptcha未使用file_get_contents进行验证

Cla*_*ire 10 php forms recaptcha

对于为什么这不起作用感到困惑.提交表单时,我收到错误消息,这意味着我的重新验证失败.

从我的形式:

<div class="g-recaptcha" data-sitekey="(site-key)"></div>
Run Code Online (Sandbox Code Playgroud)

PHP:

if(isset($_POST['g-recaptcha-response'])){
      $captcha=$_POST['g-recaptcha-response'];
    }

$secretKey = "(secret-key)";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) === true) {
    echo '<h3>Thanks for your message!</h3>';
} else {
    echo '<h3>Error</h3>';
    }
Run Code Online (Sandbox Code Playgroud)

Yem*_*iez 26

reCaptcha文档明确指定必须通过POST发送https://www.google.com/recaptcha/api/siteverify请求的参数.您可以使用CURL.

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'secret' => $secretKey,
        'response' => $captcha,
        'remoteip' => $_SERVER['REMOTE_ADDR']
    ],
    CURLOPT_RETURNTRANSFER => true
]);

$output = curl_exec($ch);
curl_close($ch);

$json = json_decode($output);

// check response...
Run Code Online (Sandbox Code Playgroud)

  • @汤姆嘿!检查如下:`if(isset($ json-> success)&& $ json-> success){echo'shaccess'; } else {echo'error'; 这应该有效,但是如果你想``json`是一个关联数组,那么为`json_decode`添加一个值为true的第二个参数,这将返回一个关联数组而不是一个对象:) (6认同)

小智 8

不要用file_get_contents.谷歌建议使用POST请求.您可以使用以下行中的内容

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'secret' => $secretKey,
        'response' => $captcha
    )
));
$response = curl_exec($curl);
curl_close($curl);

if(strpos($response, '"success": true') !== FALSE) {
    echo '<h3>Thanks for your message!</h3>';
} else {
    echo "<h3>Error</h3>";
}
Run Code Online (Sandbox Code Playgroud)

编辑

通过使用该json_decode功能,Yemiez回答(刚刚让我在角落里)更好地处理响应部分.

编辑 只是修正了一个错字