'file_get_contents() returning false for Google reCAPTCHA v3
I have been trying to implement Google reCAPTCHA v3 by using the following PHP source code:
<script src="https://www.google.com/recaptcha/api.js?render=6Ldl-98fAAAAAKRPodblUlTcVgvrfWZ_8lODjmZA"></script>
<?php
if(isset($_POST) && isset($_POST["btnSubmit"]))
{
$secretKey = '6Ldl-98fAAAAAD3ekajHHVBi2X4fZTW37bI5IGUN';
$token = $_POST["g-token"];
$ip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = array('secret' => $secretKey, 'response' => $token, 'remoteip'=> $ip);
// use key 'http' even if you send the request to https://...
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data)
));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
if($response->success)
{
echo '<center><h1>Validation Success!</h1></center>';
}
else
{
echo '<center><h1>Captcha Validation Failed..!</h1></center>';
}
}
?>
The problem is that every time I run this and step through the code line by line, I notice that the file_get_contents() function is always returning false and is assigning false to the '$result' variable. Why is this?
$result = file_get_contents($url, false, $context);
I would appreciate any advice that I can get.
Solution 1:[1]
From docs: 'null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.'
Show us $response, so var_dump($response). In recaptcha v2 i had empty string or token lately. That's why I ask for response, json decode will decode if there is proper json value.
I'd bet you get empty result and json_decode fails.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Elboyler |