Simple PHP cache technique


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

This is a little code snippet that I use in almost every project that isn’t based on a popular CMS. 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.


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. ?>

URL: http://wesbos.com/simple-php-page-caching-technique/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.