Skip to content

Instantly share code, notes, and snippets.

@pwenzel
Created January 5, 2012 22:35
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 pwenzel/1567716 to your computer and use it in GitHub Desktop.
Save pwenzel/1567716 to your computer and use it in GitHub Desktop.
PHP Caching Snippet adapted from Peter Karman
<?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