Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Caching Web Page Output (0 Comments)
Admin: Posted Date: April 4, 2010

In this situation, instead, we are going to create a dynamic solution. Some code that you can include at the top of every PHP file ensures that the page only gets generated once per hour for each script.

This script can be customized to meet your own needs, such as allowing for cookies or even sessions to be considered in whether a page is different.To demonstrate how this is used, Listing 9.6.2 is included that just uses the cache mechanism and outputs the current time.If the cache works,the output will not change for an hour.The test page assumes that you saved the previous code in a file called buffer.php.

Caching Web Page Output for Server Optimization
Often PHP is used to generate pages that do not change all that often. It isn’t that PHP is used to make every page different for every user but that the page is simply built dynamically. In these situations, it is often the case that, the page really doesn’t change all that often, perhaps only once a day, if that. In these cases, therefore, it is a waste of CPU time to regenerate the web page for every user.
One solution is to not have your PHP pages accessed directly but to have a separate script that uses your PHP to generate the output and save that to a file.Then have the web server reference that file.This works, but adds an extra step that you must remember to do.


In this situation, instead, we are going to create a dynamic solution. Some code that you can include at the top of every PHP file ensures that the page only gets generated once per hour for each script (see Listing 9.6.1).The function goes one step further and understands that different GET and POST parameters generate different pages and will therefore generate separate cached copies for each different combination of GET and POST parameters that occur.
Listing 9.6.2 How To Use Internal Page Caching
<?php
// Include the caching library:
require_once '09c06-1.php';
//require_once 'cache.php';
// Initialize the caching:
cache_page();
// Now let's just echo out the date. If caching
// works, when you reload this page, the date
// will not change until an hour has passed:
date_default_timezone_set('America/New_York');
echo date(DATE_RSS, time());
?>

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: