Created
January 5, 2012 22:35
-
-
Save pwenzel/1567716 to your computer and use it in GitHub Desktop.
PHP Caching Snippet adapted from Peter Karman
This file contains 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
<?php | |
// Sample Usage | |
$uri_to_fetch = 'http://example.tld/path/to/uri'; | |
$cache_on = true; | |
$cache_key = md5( $uri_to_fetch ); | |
$cache_ttl = 60 * 15; // 15 minutes | |
$cache_file = '/tmp/example.tld/'.$cache_key; | |
if (file_exists($cache_file) && | |
(time() - $cache_ttl) < filemtime($cache_file) && | |
$cache_on | |
) { | |
// use the cache | |
$content = file_get_contents($cache_file); | |
} | |
else { | |
// fetch the page and cache it | |
$content = cache_file_get_contents($uri_to_fetch, $cache_file); | |
} | |
// Cache-Wrapper for file_get_contents | |
function cache_file_get_contents($uri, $cache_file) { | |
if (!file_exists(dirname($cache_file))) { | |
mkdir(dirname($cache_file)); | |
} | |
$old_umask = umask(0007); // group-write-able, no world access | |
if (!$fp=fopen($cache_file, 'w')) { | |
throw new Exception('Error opening cache file'); | |
exit(); | |
} | |
if (!flock($fp, LOCK_EX)) { | |
throw new Exception('Unable to lock file'); | |
exit(); | |
} | |
$buffer = file_get_contents($uri); | |
// sanity check | |
if (!strlen($buffer)) { | |
// throw exception? read existing cache file? | |
} | |
if (!fwrite($fp, $buffer)) { | |
throw new Exception('Error writing to cache file'); | |
exit(); | |
} | |
flock($fp, LOCK_UN); | |
fclose($fp); | |
umask($old_umask); // restore | |
return $buffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment