-
-
Save siamware/eb736513c8035701c1e05e87c216c20b to your computer and use it in GitHub Desktop.
php caching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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