#native_company# #native_desc#

Compressing and Caching Dynamic Output Page 4

By Luis Argerich
on January 24, 2001

Caching PHP output

When PHP4 didn’t exist and I had to use PHP3, I was
very interested in the development of some sort of caching mechanism
for the output of php scripts to reduce the load of the database,
access to the filesystem, etc. There was no good way to do that in PHP3,
but with output buffering, it is easy in php4.
This is a simple example:


//Construct a filename for the requested URI


if((!file_exists("/cache/$cached_file"))||(!is_valid("/cache/$cached_file"))) {

// is_valid validates the cache, you can check for expiration

    // or particular conditions in that function.

    // If there's no file or it's invalid we generate the output



    // Output stuff here... 

    $contents ob_get_contents();





//Output the file here we are sure the file exists.



This is a simple example. By using output buffering, you can build
a very advanced, content-generation system, using caching mechanisms different
for different blocks or applications, etc. It is up to you.