Simple Page Caching

/ Published in: PHP
Save to your folder(s)

Use this to page cache your pages. Will save page output to a file. Will check file modified date to get from file or retrieve again

Copy this code and paste it in your HTML
  1. <?php
  2. // define the path and name of cached file
  3. $cachefile = 'cached-files/'.date('M-d-Y').'.php';
  4. // define how long we want to keep the file in seconds. I set mine to 5 hours.
  5. $cachetime = 18000;
  6. // Check if the cached file is still fresh. If it is, serve it up and exit.
  7. if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
  8. include($cachefile);
  9. }
  10. // if there is either no file OR the file to too old, render the page and capture the HTML.
  11. ?>
  12. <html>
  13. output all your html here.
  14. </html>
  15. <?php
  16. // We're done! Save the cached content to a file
  17. $fp = fopen($cachefile, 'w');
  18. fclose($fp);
  19. // finally send browser output
  20. ?>

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.