irwan

Simple PHP Page Caching Technique

Mar 16th, 2012
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.05 KB | None | 0 0
  1. Since its fairly expensive to hit the database on every page load, its a smart idea to cache the plain HTML markup of your page and serve that up. You can set how often the page cache is flushed out depending on how often you update your site’s content.
  2.  
  3. <?php
  4.     // define the path and name of cached file
  5.     $cachefile = 'cached-files/'.date('M-d-Y').'.php';
  6.     // define how long we want to keep the file in seconds. I set mine to 5 hours.
  7.     $cachetime = 18000;
  8.     // Check if the cached file is still fresh. If it is, serve it up and exit.
  9.     if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
  10.     include($cachefile);
  11.         exit;
  12.     }
  13.     // if there is either no file OR the file to too old, render the page and capture the HTML.
  14.     ob_start();
  15. ?>
  16.     <html>
  17.         output all your html here.
  18.     </html>
  19. <?php
  20.     // We're done! Save the cached content to a file
  21.     $fp = fopen($cachefile, 'w');
  22.     fwrite($fp, ob_get_contents());
  23.     fclose($fp);
  24.     // finally send browser output
  25.     ob_end_flush();
  26. ?>
Advertisement
Add Comment
Please, Sign In to add comment