Burrito411
Burrito411

Reputation: 431

Can I retry file_get_contents() until it opens a stream?

I am using PHP to get the contents of an API. The problem is, sometimes that API just sends back a 502 Bad Gateway error and the PHP code can’t parse the JSON and set the variables correctly. Is there some way I can keep trying until it works?

Upvotes: 2

Views: 6795

Answers (4)

Eric Seastrand
Eric Seastrand

Reputation: 2633

A loop can solve this problem, but so can a recursive function like this one:

function file_get_contents_retry($url, $attemptsRemaining=3) {
    $content = file_get_contents($url);
    $attemptsRemaining--;

    if( empty($content) && $attemptsRemaining > 0 ) {
        return file_get_contents_retry($url, $attemptsRemaining);
    }

    return $content;
}

// Usage:
$retryAttempts = 6; // Default is 3.
echo file_get_contents_retry("http://google.com", $retryAttempts);

Upvotes: 2

bishop
bishop

Reputation: 39434

Based on your comment, here is what I would do:

  1. You have a PHP script that makes the API call and, if successful, records the price and when that price was acquired
  2. You put that script in a cronjob/scheduled task that runs every 10 minutes.
  3. Your PHP view pulls the most recent price from the database and uses that for whatever display/calculations it needs. If pertinent, also show the date/time that price was captured

The other answers suggest doing a loop. A combo approach probably works best here: in your script, put in a few loops just in case the interface is down for a short blip. If it's not up after say a minute, use the old value until your next try.

Upvotes: 1

Jivan
Jivan

Reputation: 23078

This is not an easy question because PHP is a synchronous language by default.

You could do this:

$a = false;
$i = 0;
while($a == false && $i < 10)
{
    $a = file_get_contents($path);
    $i++;
    usleep(10);
}

$result = json_decode($a);

Adding usleep(10) allows your server not to get on his knees each time the API will be unavailable. And your function will give up after 10 attempts, which prevents it to freeze completely in case of long unavailability.

Upvotes: 11

Sam
Sam

Reputation: 20486

Since you didn't provide any code it's kind of hard to help you. But here is one way to do it.

$data = null;

while(!$data) {
    $json = file_get_contents($url);
    $data = json_decode($json); // Will return false if not valid JSON
}

// While loop won't stop until JSON was valid and $data contains an object
var_dump($data);

I suggest you throw some sort of increment variable in there to stop attempting after X scripts.

Upvotes: 6

Related Questions