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

  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.