PHPBuilder - Caching Web Page Output for Server Optimization



RSS Twitter
Articles Site Operation

Caching Web Page Output for Server Optimization

by: Eli White III and Jonathan Eisenhamer
|
August 23, 2006

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.1 An Output Caching Library—Filename: cache.php
[ code listing ]
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.
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());
?>

This article is taken from the chapter titled, "Web Page Creation/XHTML/CSS", which is excerpted from the new book, PHP 5 in Practice, authored by Eli White III and Jonathan Eisenhamer. Copyright 2007 by Sams Publishing. ISBN 0672328887. Reprinted with permission by Pearson Education; All rights reserved. A complete Table of Contents is available online.

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Eli White III and Jonathan Eisenhamer

Comment:



Comment:

(Maximum characters: 1200). You have characters left.