Here’s a variation of a PHP caching script. One of the things I frequently find myself doing for page(s) that take a long time to render, especially if they are a long running process, is to generally save a recent cached page (or more specifically) cached content and serving that up, when I need to have an immediate page appear.
Grab this on GitHub: https://github.com/acbrandao/PHP/tree/master/simple_cache
Here ‘s a quick sample:
<?php $cache_file = 'URI to cache file'; $cache_life = '120'; //caching time, in seconds $filemtime = @filemtime($cache_file); // returns FALSE if file does not exist @ prevents error display if (!$filemtime or (time() - $filemtime >= $cache_life)){ ob_start(); resource_consuming_function(); file_put_contents($cache_file,ob_get_flush()); }else{ readfile($cache_file); } ?>
Abrandao. good article, just implemented it on one section of my site. I have an isue though. My site uses user generated content. If a user creates a page, or comment or anything with the string for instance.
It might be better to store it in database with a timestamp and run a cron periodically to remove expired entries.
Step up to a real caching solution, for websites, use a proven system like for caching check Varnish or Squid
Agreed, CoderX has it right, why re-invent the wheel, there are many proven caching solutions out there both open soure and commercial, the quick caching here won’t scale if the site gets hammered.