Created
August 11, 2018 11:34
-
-
Save motyar/480831fb693df54ec0739cf952c8eaae to your computer and use it in GitHub Desktop.
Simple caching with 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 | |
// define the path and name of cached file, | |
$cachefile = 'cache/'.urlencode($_SERVER['REQUEST_URI']).'.txt'; | |
// define how long we want to keep the file in seconds. | |
//$cachetime = 60*60*24; | |
$cachetime = 4; | |
// Check if the cached file is still fresh. If it is, serve it up and exit. | |
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) { | |
echo "<h1>from cache</h1>"; | |
include($cachefile); | |
exit; | |
} | |
// if there is either no file OR the file to too old, render the page and capture the HTML. | |
ob_start(); | |
// Put all contents here. | |
echo "page contents at ".time(); | |
// We're done! Save the cached content to a file | |
file_put_contents($cachefile, ob_get_contents()) or exit("Error! Check if cachefile is writable"); | |
ob_end_flush(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment