Search code examples
phpapachecachingindexingapc

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?

Solution

  • I went with a slight variation on Rowlf's and jamietelin's answer.

    Create 3 files:

    index.html

    <meta http-equiv="refresh" content="0;url=/index_update.php" />
    

    index.php

    <?php // do all your normal stuff ?>
    

    index_update.php

    <?php
    
    $file = "index.html";
    $time = 60 * 10 - (time() - filemtime($file));
    
    # this is on the first install 
    if (filemtime($file) != filectime($file))
        $time = 0;
    
    if ($time > 0) {
        die("Data was already updated in the 10 minutes. Please wait another " . ($time) . " seconds.");
    }
    
    ob_start();
    require "index.php";
    $data = ob_get_contents();
    
    $fp = fopen($file, "w");
    fwrite($fp, $data);
    fclose($fp);
    
    header("Location: /");
    

    And then a cronjob:

    */15 * * * * curl http://example.com/index_update.php
    

    So, if someone stumbles on the page after a production push, they will just transparently create a new index.html for you, otherwise, your cronjob will make it every 15 minutes.

    Just make sure index.html is writable by your apache server. If that sounds scary, then just make your cronjob run php index_update.php as another user with write priviledges to index.html. You won't have access to all the apache environment though.

    Hope this helps, comments are welcome.