PHPBuilder - Compressing and Caching Dynamic Output Page 4



RSS Twitter
Articles Tricks And Hacks

Compressing and Caching Dynamic Output - Page 4

by: Luis Argerich
|
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:

<?php

//Construct a filename for the requested URI
$cached_file=md5($REQUEST_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
    
ob_start();
    
ob_implicit_flush(0);

    
// Output stuff here... 

    
$contents ob_get_contents();
    
ob_end_clean();

    
$fil=fopen($cached_file,"w+");
    
fwrite($fil,$contents,$strlen($contents));
    
fclose($fil);


//Output the file here we are sure the file exists.
readfile($cached_file);

?>
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.

« Previous Page
1
|
2
|
3
|
4
|
5
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Luis Argerich

Comment:



Comment:

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