Skip to content

Instantly share code, notes, and snippets.

@siamware
Forked from mibrahim/cache.php
Created April 9, 2018 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siamware/eb736513c8035701c1e05e87c216c20b to your computer and use it in GitHub Desktop.
Save siamware/eb736513c8035701c1e05e87c216c20b to your computer and use it in GitHub Desktop.
php caching
https://davidwalsh.name/php-cache-function
/* gets the contents of a file if it exists, otherwise grabs and caches */
function get_content($file,$url,$hours = 24,$fn = '',$fn_args = '') {
//vars
$current_time = time(); $expire_time = $hours * 60 * 60; $file_time = filemtime($file);
//decisions, decisions
if(file_exists($file) && ($current_time - $expire_time < $file_time)) {
//echo 'returning from cached file';
return file_get_contents($file);
}
else {
$content = get_url($url);
if($fn) { $content = $fn($content,$fn_args); }
$content.= '<!-- cached: '.time().'-->';
file_put_contents($file,$content);
//echo 'retrieved fresh from '.$url.':: '.$content;
return $content;
}
}
/* gets content from a URL via curl */
function get_url($url) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment