| <?php |
| /* =========================================================================== |
| ===== Title: Basic caching script using output buffering |
| ===== Created by: Scott Thompson |
| ===== WebSite: www.CoderProfile.com |
| ===== Date Created: 10th January 2008 |
| ===== Updates & Discussion & More Information can be found on my profile: |
| ===== www.coderprofile.com/coder/VBAssassin |
| =========================================================================== */ |
| |
| //===================================== |
| //CACHE SETTINGS |
| //===================================== |
| define('CACHE_ENABLED', true); |
| define('CACHE_EXTENSION', '.cache'); |
| define('CACHE_EXPIRE_HOURS', 1); |
| |
| //===================================== |
| //=== HANDLE CACHING OF THIS PAGE |
| //===================================== |
| |
| if (CACHE_ENABLED == true) { |
| |
| //add the content to the cache file |
| function save_to_cache($content) { |
| |
| //save the content just sent to the buffer to a cache file |
| $fh = fopen($_SERVER['SCRIPT_FILENAME'] . CACHE_EXTENSION, 'w+'); |
| fwrite($fh, $content); |
| fclose($fh); |
| |
| //return the current content back to the buffer |
| return $content; |
| |
| } |
| |
| //check if the cache is ok to use (exists and not expired) |
| if (file_exists($_SERVER['SCRIPT_FILENAME'] . CACHE_EXTENSION)) { |
| |
| //check the data the cache was saved |
| $last_modified = filemtime($_SERVER['SCRIPT_FILENAME'] . CACHE_EXTENSION); |
| if ($last_modified > time() - (3600 * CACHE_EXPIRE_HOURS) ) { |
| |
| //display what is in the cache file |
| print file_get_contents($_SERVER['SCRIPT_FILENAME'] . CACHE_EXTENSION); |
| |
| //cache loaded and displayed so prevent the rest of this page loading |
| die(); |
| |
| } else { |
| |
| //cache has expired so delete it |
| unlink($_SERVER['SCRIPT_FILENAME'] . CACHE_EXTENSION); |
| |
| } |
| } |
| |
| //enabled caching of this page |
| ob_start("save_to_cache"); |
| |
| } |
| |
| //===================================== |
| //===================================== |
| //===================================== |
| |
| ?> |
| |
| The rest of your page loads as normal below this... and will be cached depending on your cache settings. |