The function is very simple, that is, to cache the entire page, you can set the cache time, You Can cache a specific URL, for example: test. php? Id = 12. When the target file is updated, such as test. php, the cached file is also updated, even if it is still in the cache period.
Class cache
{
Var $ cache_dir =./cache/; // This is the directory where the cache files will be stored;
Var $ cache_time = 120; // How much time will keep the cache files in seconds.
Var $ caching = false;
Var $ file =;
Function cache ()
{
// Constructor of the class
$ This-> file = $ this-> cache_dir. urlencode ($ _ SERVER [REQUEST_URI]);
If (file_exists ($ this-> file) $ expired = $ this-> check_expire ();
Else $ expired = false;
If (file_exists ($ this-> file) & (filemtime ($ this-> file) + $ this-> cache_time)> time ()&&! $ Expired)
{
// Grab the cache:
$ Handle = fopen ($ this-> file, "r ");
Do {
$ Data = fread ($ handle, 8192 );
If (strlen ($ data) = 0 ){
Break;
}
Echo $ data;
} While (true );
Fclose ($ handle );
Exit ();
}
Else
{
// Create cache:
$ This-> caching = true;
Ob_start ();
$ Now = time ();
Echo "<! -- Last modified: ". $ now." --> ";
}
}
Function close ()
{
// You shoshould have this at the end of each page
If ($ this-> caching)
{
// You were caching the contents so display them, and write the cache file
$ Data = ob_get_clean ();
Echo $ data;
$ Fp = fopen ($ this-> file, w );
Fwrite ($ fp, $ data );
Fclose ($ fp );
}
}
Function check_expire (){
$ Fp = fopen ($ this-> file, "r ");
Preg_match ("/:( [d] +)-/", fread ($ fp, 200), $ time );
$ Modify_time = $ time [1];
If ($ modify_time <filemtime ($ _ SERVER [SCRIPT_FILENAME]) {
Return true;
}
Else {
Return false;
}
}
}
Usage:
// Example:
$ Ch = new cache ();
Echo date ("d m j G: I: s T Y ");
$ Ch-> close ();