Patrioticcow
Patrioticcow

Reputation: 27038

curl, how to use file_get_contents?

i have a php script like this:

    <?php
$likes = 'https://graph.facebook.com/google';
$fb = file_get_contents($likes);
$fb_array=json_decode($fb,true);
$all_likes = $fb_array['likes'];
$english_format = number_format($all_likes);
?>

what happens sometimes is that the url is failing and i get something like this:

Warning: file_get_contents(https://graph.facebook.com/google) [function.file-get-contents]: failed to open stream: HTTP request failed! in /var/www/html/google/index.php on line 774

I was wondering if there is a way for the code to degrade gracefully, because is bringing my entire website down.

I was thinking if there is a php or curl alternative to handle that error.

any ideas?

Thanks

edit: i could so this:

    <?php
$likes = 'https://graph.facebook.com/google';
if(!@file_get_contents($likes)){
    $english_format = 123;
} else {
$fb = file_get_contents($likes);
$fb_array=json_decode($fb,true);
$all_likes = $fb_array['likes'];
$english_format = number_format($all_likes);
    } 
?>

but it still slows down my website

Upvotes: 0

Views: 365

Answers (3)

netcoder
netcoder

Reputation: 67695

You can handle HTTP errors with file_get_contents by using a stream context:

$context = stream_context_create(array(
    'http' => array(
         'ignore_errors' => true,
    ),
));

$fb = file_get_contents('http://www.google.com');
$code = substr($http_response_header[0], strpos($http_response_header[0], ' ')+1);

if ($code != 200) {
    // there might be a problem
}

Additionally, display_errors should be Off on production environments.

Upvotes: 1

Andrej
Andrej

Reputation: 7504

I don't like @ because this one makes code execution slower. But you can use code below because if all is ok you make two file_get_contents and it's slow

$likes = 'https://graph.facebook.com/google';
$result = @file_get_contents($likes);
if(empty($result)){
    $english_format = 123;
} else {
    $fb_array=json_decode($result,true);
    $all_likes = $fb_array['likes'];
    $english_format = number_format($all_likes);
} 

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101594

You can setup an Error Handler to catch (and politely manage) the error.

Alternatively you can @suppress the error, then just check to make sure $fb is valid before continuing.

Upvotes: -1

Related Questions