The concept to cache it’s very simple in PHP. First you should have some content on a page in order to cache it. First you should have a directory where all the cached pages are stored.
How it works?
First, we should verify if the page exists in our directory, if exists then it means that the page was saved(chached) before and we can list that page. For caching a page for a period of time we should verify if the date creation of the page cached was before the time that we want to keep the page cached, otherwise we create a fresh cached page. Here is a sample code to do this:
<?php $filetocache = "../cache/".$filename.".html"; //to cache outside root directory //time to cache the page $timecache = 3600 * 24 * 7;//// calculate a period of 1 week // Here we test if the file exists and if the cached file was created in the period we specify if (file_exists($filetocache) && (time() - $time cache < filemtime($filetocache))) { include($filetocache);//we show the page that was cached previously echo "<!-- Date cached ".date('jS F Y H:i', filemtime($filetocache))." -->n"; exit; } ob_start(); // here we start the output buffer //HERE we otput the page as html .... ?>
If it not exists we list our page and in the end we save the page to the cache directory, so next time the page is loaded we will get the content from cache directory. So if it time creation is higher then our period then we list the page and rewrite again to the cache directory. Here is the code for saving the contents output displayed on the browser:
<? ob_start(); //HERE we otput the page as html ..... $filetocache = "../dircache/".$filename.".html";//this is the page that we should cache, the filename is the name of the page $fp = fopen($filetocache, 'w'); // first open the cache file for writting fwrite($fp, ob_get_contents()); // we put the output contents that are sent to browser fclose($fp); // close the file ob_end_flush(); // for sending content to the browser ?>


















1 Comment to 'PHP cache file for a period'
April 18, 2009
[...] Log in « PHP cache file for a period [...]
Leave a comment
You must be logged in to post a comment.