Search code examples
phpjsonrecaptcha

Google reCaptcha json response return false


I have tried google captcha using PHP as following way

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

This same code has worked in PHP 5.4 But Is not working on PHP 7.0 , i don't know how to fix it, any suggestion or solution please post


Solution

  • You can try in this way. Hope it will help you.

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