Replace file_get_contents with file_get_contents_curl

Hi,

I am caching a json result from an API and saving it as a file on my server.

I have the following code that checks this files age and replaces it with a newer version if its too old.

It works great locally but is not allowed on my host due to security risks. How can I best replace this file_get_contents method with a file_get_contents_curl one? Is file_get_contents_curl the way to go? Alternatively - if there is a better way of doing this I am all ears :slight_smile:

if (time()-filemtime($url) > 1200) { // file older than 20 minutes

		$json = file_get_contents("http://service-api-url/json/", true); //getting the file content
		$decode = json_decode($json, true); //getting the file content as array

		$fp = fopen('data/myjson.json', 'w');
		fwrite($fp, json_encode($decode));
		fclose($fp);

	echo $json;

	} else {
	  // file younger than 20 minutes
		$json = file_get_contents($url);
		// echo the JSON
		echo $json;
	}

Thanks!

Implementing a file_get_contents_curl is the quick and dirty solution, but almost certainly not the best. For one, you’d also have to make a filemtime_curl. Plus any other file functions that you use on URLs. And second, a filemtime_curl and file_get_contents_curl on the same file may be a waste. These days, the overhead of an HTTP request can take more time than downloading the actual data. It would probably be more efficient to request the file, then check its headers. Though, file_get_contents_curl doesn’t give you any way to check the headers. You could implement all the logic you need using just curl functions, but that can start to get really clunky really fast. Ultimately, I recommend [URL=“http://docs.guzzlephp.org/en/latest/”]Guzzle. With it, your code could look like this:

$client = new Guzzle\\Http\\Client();
$response = $client->get('http://service-api-url/json/')->send();
$lastModififed = $response->getHeader('Last-Modified');
$decodedJson = $response->json();

Thanks Jeff!

There was me thinking this was quite a common thing to do. Ultimately I’m trying avoid unnecessary calls to the API.

I will check out Guzzle though I was hoping to avoid relying on another library.

Thanks again.