Skip to content

Instantly share code, notes, and snippets.

@mrl22
Last active June 26, 2017 10:21
Show Gist options
  • Save mrl22/0e69e8abee6a39d8158cf2f5be060d39 to your computer and use it in GitHub Desktop.
Save mrl22/0e69e8abee6a39d8158cf2f5be060d39 to your computer and use it in GitHub Desktop.
Cached cURL Request
function curl2json($url, $header_opts=array(), $cache_life=300) {
$cache_file = md5($url.json_encode($header_opts)).'.txt';
if (!file_exists($cache_file) || (time() - filemtime($cache_file)) >= $cache_life) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_FOLLOWLOCATION => FALSE,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $header_opts
));
$resp = curl_exec($curl);
file_put_contents($cache_file, $resp);
curl_close($curl);
return json_decode($resp, true);
} else {
return json_decode(file_get_contents($cache_file), true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment