Home

Wednesday, December 12, 2012

How to create a simple and efficient PHP cache

Step one: Create the top-cache.php file

<?php
$url = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $url);
$file = $break[count($break) - 1];
$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";
    include($cachefile);
    exit;
}
ob_start(); // Start the output buffer
?>
 

Step two: Create the bottom-cache.php file

<?php
// Cache the contents to a file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
?>
 

Step three: Include cache files on your page

 <?php

include('top-cache.php'); 

// Your regular PHP code goes here
echo " How to create a simple and efficient PHP cache"; 
 
include('bottom-cache.php');
?>

 

 

 

No comments:

Post a Comment

rathoddhirendra.blogspot.com-Google pagerank and Worth