Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to do server-side output caching in PHP?

I have a pretty complicated index.php now, and I would like to only run it once every hour. What is the best way to achieve this? Some ideas I've had

  • Put it in APC with apc_store($page, 60*60*) - I feel this isn't what APC is for and will probably be doing something bad to the other parts of my site
  • Save the output to a filesystem somewhere - Then apache needs write access somewhere which might be a pain
  • Somehow setup apache to do the caching for me - Is this possible?
like image 332
Paul Tarjan Avatar asked Feb 05 '10 06:02

Paul Tarjan


1 Answers

  1. When a visitor hits your page, generate the content, send it to the user and save a static file somewhere on disk.
  2. When the next visitor comes, first look for the saved file, and if it exists, serve that rather than execute all the code in your index.php file. A basic example would be

    if (file_exists($cacheFileName))
    {
        require $cacheFileName;
        exit;
    }
    
    // here goes the rest of your index.php code
    //..
    
    // assuming your output is buffered and is contained in $output:
    echo $output;
    
    $cacheFileName = '/path/to/your/file.inc';
    file_put_contents($cacheFileName, $output);
    
  3. Set up a cron job that will delete your saved cache file from disk every hour or as often as you need to. Alternatively, in your index.php, on every page hit check how long ago the cached file was created and generate a new cache file if it's been around longer than you'd want it to. A cron job is easier to set up though.

To answer the deep philosophical question though, saving generated output to disk in separate files is probably the best way if you don't want to rely on third party caching solutions. APC is good for caching the code that will regenerate pages when needed, and memcached is definitely overkill if we're talking about a small(ish) application.

like image 85
Rowlf Avatar answered Sep 29 '22 19:09

Rowlf