Google reCaptcha json响应返回false

时间:2018-02-12 07:38:53

标签: php json recaptcha

我已尝试使用PHP的谷歌验证码如下

HTML

<div class="col-md-12">
     <div class="form-group">
        <div class="g-recaptcha" data-sitekey="6Lf2yUUUAAksikja1XQNtIOqIDmtzb46uHGY-Wq_sl">
        </div>
     </div>
</div>

PHP

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
    $secret = '6Lf2yUAAHvAr2QoaNHYFDG945Z6Ai7EqTg6Y71';
    //get verify response data
    $verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret=&response=" . rawurlencode($_POST['g-recaptcha-response']) . "&remoteip=" . rawurlencode($_SERVER['REMOTE_ADDR']));

    $responseData = json_decode($verifyResponse);
    if($responseData->success){

    } else {
      echo 'Robot verification failed, please try again.';
    }
}

这个代码在PHP 5.4中有效但是不能在PHP 7.0上工作,我不知道如何修复它,任何建议或解决方案请发布

2 个答案:

答案 0 :(得分:2)

你可以这样试试。     希望它会对你有所帮助。

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
  $privatekey = "XXXXXXXXXXXXXXXXXXXXXX";
  $captcha = $_POST['g-recaptcha-response'];
  $url = 'https://www.google.com/recaptcha/api/siteverify';
  $data = array(
      'secret' => $privatekey,
      'response' => $captcha,
      'remoteip' => $_SERVER['REMOTE_ADDR']
  );

  $curlConfig = array(
      CURLOPT_URL => $url,
      CURLOPT_POST => true,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POSTFIELDS => $data
  );

  $ch = curl_init();
  curl_setopt_array($ch, $curlConfig);
  $response = curl_exec($ch);
  curl_close($ch);
  $jsonResponse = json_decode($response);
  if ($jsonResponse->success === true) {

  }
  else {
      $errMsg = 'Robot verification failed, please try again.';
    }
} else{

  $errMsg = 'Please click on the reCAPTCHA box.';
}

答案 1 :(得分:0)

如果您的验证码经过两次验证,您可能会遇到timeout-or-duplicate问题。以追加模式将日志保存在文件中,并检查您是否正在验证验证码两次。

例如,请查看以下内容:

$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response'])

file_put_contents( "logfile",  $verifyResponse, FILE_APPEND );

现在,检查上面创建的日志文件并尝试检查验证码是否已经过两次验证。