GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Tuesday, April 5, 2011

PHP - Caching The Page

<?php

    date_default_timezone_set('Asia/Jakarta');
   
    // get the url as file name
    $file = md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   
    $cachefile = 'cache/'.$file.'.html';
   
    // get this page file name
    $file_page = __FILE__;

    if (file_exists($cachefile) && (filemtime($file_page)) < filemtime($cachefile)) {

        // this must be included because the file cache comes from here.
        include($cachefile);

        echo "<!– Cached ".date('H:i', filemtime($cachefile))." –>n";

        exit;

    }

    ob_start(); // start the output buffer

?>

<h1>...Everything Here Is Cached...</h1>


<?php

    $fp = fopen($cachefile, 'w'); // open the cache file for writing

    fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file

    fclose($fp); // close the file

    ob_end_flush(); // Send the output to the browser

?>

Share/Bookmark

No comments:

Post a Comment