HOWTO: Create a cache file in PHP
In this site, especially in the home, There are some information boxes, automatically displaying the latest blog posts, The latest comments, latest video on Youtube, my last bike activities, and the like.
Each time these boxes are loaded, in theory, runs the code that allows to show that output. Indeed, to avoid enlarging the loading time and overloading the site, is more convenient to create files CACHE, that will allow us to keep the output already developed, for a certain number of hours to our pleasure.
So, for a limited period of time, will load the output without having to perform lengthy operations in PHP / JSON / XML, or whatever else will serve the purpose.
This is the model that I use usually:
<? $expiretime=300; // cache expire time in minutes $cachename="file.cache"; //name of the cachefile //create the cachefile if it doesn't exist if (!file_exists($cacheName)) { $create = fopen($cacheName, 'W'); chmod ("$cacheName", 0644); //set chmod 644 fclose($create); } // Is the file older than $expiretime, or the file is new/empty? $FileAge = time() - filectime($cacheName); // Calculate file age in seconds if ($FileAge > ($expiretime * 60) || 0 == filesize($cacheName)) { //do something [...] //[...] // Now refresh the cachefile with newer content $output = //youroutput; $handle = fopen($cacheName, 'wb'); fwrite($handle, $output); } //cachefile is fresh enough... outputting data $data=file_get_contents($cacheName); echo $data; ?>
In $ expiretime you set the number of minutes within which you must use the file cache, and after that you will proceed to update.
I left the comments in English, to allow a wider use of this script.
Any action parsing, or whatever else is needed to produce the output, is inserted where I write “//do something”.
The line:
write($handle, $output);
will write the contents of $ output in the file cache.
E'uno script that I wrote quite a bit’ time ago, but it is always useful…
Any feedback is welcome!