Thursday 9 July 2015

simple and efficient PHP cache Create

When working on php websites made from scratch and without a framework, speed can often be an issue. Caching is extremely useful in order to speed up PHP webpages. In this article, I’ll show you a super easy and efficient way to dynamically cache php pages that need to be faster.

 Create the cache.php file 
We need to create files. Here’s the first one: Create a new file named cache.php and paste the code below in it.

<?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
?>
 
So, what this code does? The first 5 lines create the cached file name according to the current php file. So, if you’re using a file named list.php, the cached file will be named cached-list.html.
Line 6 creates a $cachetime variable which determines the life of the cache.
Lines 9 to 13 are a conditional statement which look for a file named $cachefile. If the file is found, a comment is inserted (line 10) and the $cachefile file is included. Then, the exit statement stops the execution of the script and the file is sent to the client brother. Which means that if a static file is found, no php code is interpreted by the server.
Line 14 creates a buffer, if the $cachefile file isn’t found. That’s all for the cache.php file.
Create the cache_1.php file  
Now, create a second php file, named cache_1.php and paste the code below in it.
<?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
?>
 
If a file named $cachefile isn’t found on your server, this code is executed and create the file, so next time the page will be called, the $cachefile static file will be served to the client browser instead of executing the whole PHP file.  
Include cache files on your page
Now that you have created the two necessary files, you simply have to include them on the php page you wish to cache. As you probably guessed, the cache.php file must be included in the beginning of your php page and the cache_2.php at the end, as shown below: 
 
<?php

include('cache.php'); 

// Your regular PHP code goes here

include('cache_2.php');
?>
Now if you test the cache on a slow page, you’ll be amazed by how faster the page is. This easy cache is my favorite solution when working on “from scratch” PHP websites. 
 

No comments:

Post a Comment