file_get_contents vs cURL

There is a code snippet suggested to use with the report API which uses file_get_contents

It works, but when the server is unreachable it generates an error and, for some reason, I was not able to catch that error or convert it into an exception (exceptions go through a dispatcher in our application and it was way too complicated).
I tried it with a timeout:
$api_response = file_get_contents($api_url, false, stream_context_create(array(‘http’=>array(‘timeout’ => 2))));
but still got an error.

So, I think it’s better to do it this way:


// Use cURL to hit the API
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$api_response = curl_exec($ch);
curl_close($ch);

if ($api_response) {
	$api_data = unserialize($api_response);
	return $api_data;
} else {
// The report server is unreachable - ignore and allow the user to get on with whatever he was doing.
	return false;
}