0

Here's the code I am using:

<?php
    $interval = 5 * 60;
    $filename = "cache/".basename( rtrim( $_SERVER["REQUEST_URI"], '/' ) ).".cache";

    if ( file_exists( $filename ) && (time() - $interval) < filemtime( $filename ) ) {
        readfile( $filename );
        exit(); 
    }

    ob_start(); 


    include 'dynamicpage.php'; 
?>



<?php
    // More page generation code goes here

    $buff = ob_get_contents(); // Retrive the content from the buffer

    // Write the content of the buffer to the cache file
    $file = fopen( $filename, "w" );
    fwrite( $file, $buff );
    fclose( $file );

    ob_end_flush(); // Display the generated page.
?>

Currently, if the cached page is over 5 minutes old, this script would generate a new cache file to replace the old one. Is there any way I can have the old cache display first and have the new cached page be generated in the background? My host is weak sauce so it takes forever to wait for the page to complete loading.

tshepang
  • 12,111
  • 21
  • 91
  • 136

3 Answers3

1

I would set a crontab to process the page every 5 minutes, and always serve your users the cached page.

If you cannot set a crontab, you can output a hidden iframe with the dynamic page loading in there, so the page loads quickly, but another instance is loading in the background (not a very neat solution, but works).

Green Black
  • 5,037
  • 1
  • 17
  • 29
  • This is a reasonable solution. Don't make the client wait while you read one page of content from disk and then potentially write a whole other page of content to disk. Just create a script you can run via cron that will build you page cache. – Mike Brant Feb 22 '13 at 23:24
  • Thanks, i think this is the best solution. I was looking for a fix that didnt involve crontab because im running on a windows server. Im switching over to a linux server soon. Thanks everyone for the replies. – user1949940 Feb 23 '13 at 22:54
  • Windows servers have crontabs too, but they are called scheduled tasks. You can set a task to open your webpage every 5 minutes (maybe with a _GET key to trigger the rebuild of your cache) – Green Black Feb 25 '13 at 17:20
1

Sounds like you need an asynchronous PHP request. Essentially what this does is trigger another script to run alongside your current one. @John has the right idea, but a crontab is only one way of running the caching process asynchronously. The downside to his solution is that it will run every 5 minutes, whether it's needed or not.

There are a number of libraries and other bits and bobs that will help you to set up async PHP processing, but again as @John says, it gets a little involved.

Here are a few resources to help with this:

Community
  • 1
  • 1
adomnom
  • 564
  • 2
  • 9
1

The Smarty Template Engine is a simple and small tool that has a lot of built in cache functionality without rules of a framework. http://www.smarty.net/

skrilled
  • 5,350
  • 2
  • 26
  • 48