Summary of php page cache methods

Source: Internet
Author: User
This article mainly introduces the php page caching method. The example summarizes the usage of common page caching functions and provides a complete cache instance, which has some reference value, for more information about how to cache php pages, see the examples in this article. Share it with you for your reference. The specific analysis is as follows:

In php page cache, ob functions are mainly used, such as ob_start (), ob_end_flush (), ob_get_contents (), but more advanced caching does not use these functions, an example is provided at the end of this article.

Let's take a look at the frequently-used ob series functions in the cache:

Ob_start ():Indicates the start of page cache. the content of this function until ob_end_flush () or ob_end_clean () is saved in the page cache;

Ob_get_contents ():It is used to obtain the content in the page cache. after obtaining the content, we can do whatever we want to do. we can filter fields and match the content ~~~

Ob_end_flush ():Indicates that the page cache is complete and verified by me. the cached content is output to the current page, that is, the cached content can be displayed.

With these three php functions, you can implement powerful functions. if the database query volume is large, you can use cache to solve this problem.

The following is the encoding section.

1. the initialization function is generally used to set the page cache path and the cache file naming format. you can customize it according to your preferences. the ID used here is the encrypted $ _ SERVER [REQUEST_URI] parameter, this function has an if judgment. if the cache period is not passed, the cached file is loaded. Otherwise, the source file is loaded. the code is as follows:

The code is as follows:

Function page_init ()
{
$ Url = $ _ SERVER ['request _ URI ']; // suburl. this parameter is generally unique.
$ Pageid = md5 ($ url );
$ Dir = str_replace ('/', '_', substr ($ _ SERVER ['script _ name'], 1,-4 ));
// Directory naming, such as exp_index
If (! File_exists ($ pd = PAGE_PATH. $ dir. '/') @ mkdir ($ pd, 0777) or die ("$ pd directory creation failed ");
// Such as cache/page/exp_index/
Define('page_file', paipd.w.pageid.'.html ');
// Such as cache/page/exp_index/cc8ef22b405566745ed21305dd248f0e.html
$ Contents = file_get_contents (PAGE_FILE); // Read

If ($ contents & substr ($ contents, 13, 10)> time () // corresponds to the custom header added to the page_cache () function
{
Echo substr ($ contents, 27 );
Exit (0 );
}
Return true;
}


2. page cache function. here we use a technique to add a header information-expiration time in the content of the cached file. Therefore, you only need to compare the expiration time in the header with the current time each time, in the page_init () function, you can determine whether the cache has expired. the code is as follows:

The code is as follows:

Function page_cache ($ ttl = 0)
{
$ Ttl = $ ttl? $ Ttl: PAGE_TTL; // The cache time. the default value is 3600 s.
$ Contents = ob_get_contents (); // Obtain the content from the cache
$ Contents =" N ". $ contents;
// Add the custom header: Expiration Time = generation time + cache time
File_put_contents (PAGE_FILE, $ contents); // write to the cache file
Ob_end_flush (); // release the cache
}


3. use the function. Note that the two functions are executed in sequence, and do not forget ob_start (). The code is as follows:

The code is as follows:

<? Php
Page_init (); // page cache initialization
Ob_start (); // enable cache

... // Code segment

Page_cache (60); // usually the last row

?>


Example 2: Below is an example to illustrate the PHP page cache technology. the code is as follows:

The code is as follows:

<? Php
$ _ Time = 10;
$ Dir = "D: \ php \";

Function cache_start ($ _ time, $ dir)
{
$ Cachefile = $ dir. '/'.sha1(pai_server}'request_uri'{}.'.html ';
$ Cachetime = $ _ time;
Ob_start ();
If (file_exists ($ cachefile) & (time ()-filemtime ($ cachefile) <$ cachetime ))
{
Include ($ cachefile );
Ob_end_flush ();
Exit;
}
}

Function cache_end ($ dir)
{
$ Cachefile = $ dir. '/'.sha1(pai_server}'request_uri'{}.'.html ';
$ Fp = fopen ($ cachefile, 'w ');
Fwrite ($ fp, ob_get_contents ());
Fclose ($ fp );
Ob_end_flush ();
}

Cache_start ($ _ time, $ dir );
// The following is the output content, which is placed between the cache_start and cache_end methods.
For ($ I = 0; $ I <5; $ I ++)
{
Echo $ I;
Sleep (1 );
}
Cache_end ($ dir );
?>


For example, the code is as follows:

The code is as follows:

<? Php
Ob_start ();
/**
* @ Author he Minghui
* @ Copyright 2009-3-13
* @ Param string $ cache_folder slow folder
* @ Param int $ cache_create_time file cache time
* @ Example $ cache = new Esj_Cache ('./_ cache', 100)
* @ Example $ cache-> read_cache () read and output the cache
* @ Example $ cache-> creatre_cache () create a cache file (put it before the end of the file)
* @ Example $ cache-> list_file () returns the list of all cached files
* @ Example $ cache-> del_file () delete all cached files
*/

Class Esj_Cache {
Private $ cache_folder = null; // cacher folder
Private $ wroot_dir = null; // site directory
Private $ cacher_create_time = null; // The time when the cacher file was created.

Public function _ construct ($ cache_foldername, $ cacher_time = 100)
{
Ob_start ();
$ This-> wroot_dir = $ _ SERVER ['document _ root'];
$ This-> cache_folder = $ cache_foldername;
$ This-> cacher_create_time = $ cacher_time;
}

Public function read_cache ()
{
Try {
If (self: create_folder ($ this-> cache_folder ))
{
Self: get_cache (); // outputs the cached file information.
} Else
{
Echo "an error occurred while creating the cache folder! ";
Return false;
}

} Catch (Exception $ e ){
Echo $ e;
Return false;
}
}

// Test whether the cached folder exists
Private function exist_folder ($ foler)
{
If (file_exists ($ this-> wroot_dir. "/". $ foler )){
Return true;
} Else {
Return false;
}
}

// Create a new folder
Private function create_folder ($ foler)
{
If (! Self: exist_folder ($ foler ))
{
Try {
Mkdir ($ this-> wroot_dir. "/". $ foler, 0777 );
Chmod ($ this-> wroot_dir. "/". $ foler, 0777 );
Return true;
} Catch (Exception $ e)
{
Self: get_cache (); // output cache
Return false;
}
Return false;
}
Else
{
Return true;
}
}

// Read the cached file
Private function get_cache ()
{
$ File_name = self: get_filename ();
If (file_exists ($ file_name) & (filemtime ($ file_name) + $ this-> cacher_create_time)> time ()))
{
$ Content = file_get_contents ($ file_name );
If ($ content)
{
Echo $ content;
Ob_end_flush ();
Exit;
} Else
{
Echo "file reading failed ";
Exit;

}

}
}

// Returns the object name.
Private function get_filename ()
{
$ Filename = $ file_name = $ this-> wroot_dir. '/'. $ this-> cache_folder. '/'. md5 ($ _ SERVER ['query _ string']). ". html ";
Return $ filename;
}

// Create a cache file
Public function create_cache ()
{
$ Filename = self: get_filename ();
If ($ filename! = "")
{
Try {
File_put_contents ($ filename, ob_get_contents ());
Return true;
} Catch (Exception $ e)
{
Echo "failed to write cache:". $ e;
Exit ();
}
Return true;
}
}

// Retrieve all files in the cache
Public function list_file ()
{
$ Path = $ this-> cache_folder;
If ($ handle = opendir ($ path )){
While (false! ==( $ File = readdir ($ handle ))){
If ($ file! = "." & $ File! = ".."){
$ Path1 = $ path. "/". $ file;
If (file_exists ($ path1 ))
{
$ Result [] = $ file;
}
}
}
Closedir ($ handle );
}
Return $ result;
}

// Delete all files in the cache
Public function del_file ()
{
$ Path = $ this-> cache_folder;
If ($ handle = opendir ($ path )){
While (false! ==( $ File = readdir ($ handle ))){
If ($ file! = "." & $ File! = ".."){
$ Path1 = $ path. "/". $ file;
If (file_exists ($ path1 ))
{
Unlink ($ path1 );
}
}
}
Closedir ($ handle );
}
Return true;
}

}

?>

I hope this article will help you with php programming.

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.