PHP Cache
Custom PHP code that I used to cache pages like about-us, terms and privacy and contact, shipping policy, payment cancellation policy etc.unknown
php
2 years ago
1.2 kB
4
Indexable
Create a PHP file called, cache_header.php and paste the below code: <?php $url = $_SERVER["SCRIPT_NAME"]; $break = explode('/', $url); $file = end($break); $cachefile = 'cached-' . substr_replace($file, "", -4) . '.html'; $cachetime = 18000; // Serve from the cache if it is younger than $cachetime if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) { echo "<!-- Cached copy, generated " . date('H:i', filemtime($cachefile)) . " -->\n"; readfile($cachefile); exit; } ob_start(); // Start the output buffer ?> Now, create an another PHP file called, cache_footer.php and paste the below code: <?php // Cache the contents to a cache file $cached = fopen($cachefile, 'w'); fwrite($cached, ob_get_contents()); fclose($cached); ob_end_flush(); // Send the output to the browser ?> Include both files in the page you wish to create, primarily for a static content page such as 'about us' or 'terms of service', whose content is derived from the database: For example, I have included both the files in about-us.php file. <?php // pages/about-us.php include('top-cache.php'); // rest of the PHP code include('bottom-cache.php'); ?>
Editor is loading...