First, you need to create as to where you will put all your cache files, don't put it on the same directory where your files are in coz it might overwrite your pages. On this post, I created cache directory.
We can also set the cache expiry time by validating the time it was created. To check, we used time() and filemtime() functionality.
To make it work, we will put condition to check if the we have cache file and that it didn't expired yet. If okay, we will just include the file then display the contents. If not, it will capture the page then write to a file.
Please see below for the implementation. Happy coding!!
<?php
$cachefile = "cache/yourpage.html";
$cachetime = 30 * 60; // 30 minutes
// validate and check for existing cache file
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
include($cachefile);
exit;
}
// start the output stream
ob_start();
?>
<html>your page here to put into cache</html>
<?php
// save the contents to cache file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// end the output stream
ob_end_flush();
?>
No comments:
Post a Comment