Created
March 13, 2014 18:38
-
-
Save rutger1140/9534202 to your computer and use it in GitHub Desktop.
Very basic caching script for PHP
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 | |
// Example usage | |
// Set source location | |
$sourcepath = "http://mysite.com/api/call/something"; | |
// Set cache file | |
$cacheName = "apicall.cache"; | |
// Set caching time | |
$ageInSeconds = 3600; // one hour | |
echo getCacheContent($cacheName, $sourcepath, $ageInSeconds); |
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 | |
/** | |
* Simple cache method | |
* | |
* @author: Rutger Laurman | |
* Based on http://stackoverflow.com/a/5263017 | |
*/ | |
function getCacheContent($cachefile, $remotepath, $cachetime){ | |
// Toggle debug mode | |
$debug = false; | |
// Generate the cache version if it doesn't exist or it's too old! | |
if(file_exists($cachefile) && (filemtime($cachefile) > (time() - $cachetime))) { | |
if($debug){ | |
echo "DEBUG: not expired, use cache\n"; | |
} | |
} else { | |
if($debug){ | |
echo "DEBUG: expired, attempt to refresh\n"; | |
} | |
if($contents = @file_get_contents($remotepath)){ | |
@file_put_contents($cachefile, $contents, LOCK_EX); | |
if($debug){ | |
echo "DEBUG: refresh succes, cache written\n"; | |
} | |
} else { | |
if($debug){ | |
echo "DEBUG: refresh failed, using cache\n"; | |
} | |
} | |
} | |
// Get contents of cache file | |
$fileContents = @file_get_contents($cachefile); | |
if($fileContents) { | |
return $fileContents; | |
} else { | |
if($debug){ | |
echo "DEBUG: failed to get content"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would at least pass a user agent so you don't get blocked by the remote host