$file = "https://www.some-api.com/?a=get_info";
$doge = (object) json_decode(file_get_contents($file));
if ($doge == false){
echo "failure";
}
else
{
[my code]
};
Every once and a while my script will fail, not all the time, simply intermittently. PHP error indicates that it's failing at the point of getting the file contents.
My attempt here with this else statement (that has not worked), was to display something different when the contents failed to be received. Is there a simple way for me to add a failsafe, so that either the script is reloaded or a different process is run if the api fails to respond properly?
This line will never be true...
if ($doge == false){
Given that $doge
can never be false:
$doge = (object) json_decode(file_get_contents($file));
You always cast $doge
to an object. You can't do that, and still check whether it's false. You need to perform the test before the cast, because...
file_get_contents
fails, it returns false
json_decode(false)
returns NULL
(object) NULL
returns an object of type stdClass
.Therefore - it's impossible for $doge
to be false
, ever.
Try checking for failure before blindly json_decoding
the result. Then, you don't even need the (object)
cast.
$data = file_get_contents($file);
if (data) {
$doge = json_decode($data);
[my code]
} else {
echo "failure";
}
In the json_decode() documentation, it says that FALSE
represents the false value. If it doesn't find any values to translate, it returns NULL
. So be careful with that if
...
The failsafe would by
$doge = json_decode(file_get_contents($file));
if (!is_null($doge)){
[decoded OK, your code here]
}
else
{
[failsafe code here]
};