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.
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
// Include the caching library:
// Initialize the caching:
// 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:
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.