PHP is a small cache class

Source: Internet
Author: User

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.