Sample Code: Quick and Dirty PHP Cache 4

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 &gt;= $cache_life)){
ob_start();
resource_consuming_function();
file_put_contents($cache_file,ob_get_flush());
}else{
readfile($cache_file);
}
?>

4 thoughts on “Sample Code: Quick and Dirty PHP Cache

  1. Reply Jack Sep 25,2012 4:10 am

    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.

  2. Reply Brent Sep 24,2012 12:41 pm

    It might be better to store it in database with a timestamp and run a cron periodically to remove expired entries.

  3. Reply CoderX Sep 25,2012 9:41 pm

    Step up to a real caching solution, for websites, use a proven system like for caching check Varnish or Squid

    • Reply MingoBrains Sep 24,2012 5:08 pm

      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.

Leave a Reply