Site Owners Forums - Webmaster Forums

Site Owners Forums - Webmaster Forums (http://siteownersforums.com/index.php)
-   PHP / mySQL (http://siteownersforums.com/forumdisplay.php?f=10)
-   -   Super simple page caching. (http://siteownersforums.com/showthread.php?t=99924)

noahwilson 07-18-2013 08:36 AM

Super simple page caching.
 
When your project isn’t based on a CMS or framework, it can be a good idea to implement a simple caching system on your pages. The following code snippet is very simple, but works well for small websites.

PHP Code:
// define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is, serve it up and exit.
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
include($cachefile);
exit;
}
// if there is either no file OR the file to too old, render the page and capture the HTML.
ob_start();
?>

output all your html here.

// We're done! Save the cached content to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>

mridul 11-05-2013 11:53 PM

thanx for sharing.


All times are GMT -7. The time now is 10:29 AM.


Powered by vBulletin Copyright © 2020 vBulletin Solutions, Inc.