Ob_start (): The flag of page cache start, the content of this function until Ob_end_flush () or Ob_end_clean () is saved in the page cache;
Ob_get_contents (): Used to get the contents of the page cache, to get to the future, we can think how to deal with these content is all right, filter the field, matching content, can ~ ~ ~:
Ob_end_flush (): Indicates the end of the page cache. And I verify that the cached content will be output to the current page, that is, the cached content can be displayed.
With these three PHP functions, you can achieve powerful functionality. If a large number of database queries, you can use the cache to solve this problem.
Here is the coding section.
1. Initialization functions, usually set the page cache path, cache file naming format, etc., can be customized according to personal preferences. The identification ID used here is an encrypted $_server[request_uri] parameter. Finally, there is an if judgment in this function: if the cache period is not over, load the cached file, otherwise load the source file.
The code is as follows |
Copy Code |
function Page_Init () { $url = $_server[' request_uri '];//child URL, which is generally unique $pageid = MD5 ($url); $dir = Str_replace ('/', ' _ ', substr ($_server[' script_name '],1,-4)); Directory naming methods, 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 ', $pd. $pageid. HTML '); such as cache/page/exp_index/cc8ef22b405566745ed21305dd248f0e.html $contents = file_get_contents (page_file);/read out
if ($contents && substr ($contents, a) > Time ())///corresponds to the custom header added to the Page_cache () function { Echo substr ($contents, 27); Exit (0); } return true; } |
2. Page caching functions, here is a tip: Add a header information to the contents of the cached file-the expiration time, so each time you only need to compare the expiration time in the head with the current time (in the Page_Init () function) to determine whether the cache expires.
The code is as follows |
Copy Code |
function Page_cache ($ttl = 0) { $ttl = $ttl? $ttl: page_ttl;//cache time, default 3600s $contents = ob_get_contents ()//get content from cache $contents = "<!--page_ttl:". (Time () + $ttl). " -->n ". $contents; Plus custom header: Expiration time = build time + cache time File_put_contents (Page_file, $contents);//write Cache file Ob_end_flush ()//Free cache }
|
3. Function Use, note that these two functions have sequential order, and do not forget the Ob_start ()
The code is as follows |
Copy Code |
<?php Page_Init ();//Page Cache initialization Ob_start ()//Open cache
..//Code Snippet
Page_cache (60);//generally the last line
?>
|
Example 2
Here's an example to illustrate the PHP page caching technique:
The code is as follows |
Copy Code |
<?php $_time = 10; $dir = "D:\php\"; function Cache_start ($_time, $dir) { $cachefile = $dir. '/' SHA1 ($_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 ($_server[' Request_uri '). HTML '; $fp = fopen ($cachefile, ' w '); Fwrite ($FP, ob_get_contents ()); Fclose ($FP); Ob_end_flush (); } Cache_start ($_time, $dir); Here is the output, placed between the Cache_start and Cache_end two methods For ($i =0 $i <5; $i + +) { echo $i; Sleep (1); } Cache_end ($dir); ?> |
Cases
Cache using generated files
The code is as follows |
Copy Code |
<?php Ob_start (); /** * @author He Nihui * @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 cache and output * @example $cache->creatre_cache () to create a cached file (placed at the end of the file) * @example $cache->list_file () returns a 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;//cacher File creation time 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 ()//output cache file information }else { echo "Cache folder creation failed!"; 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; } } Reading cached files 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 read failed"; Exit } } } Returns the name of the file Private Function Get_filename () { $filename = $file _name= $this->wroot_dir. '/'. $this->cache_folder. ' /'. MD5 ($_server[' query_string '). ". HTML "; return $filename; } Create a cached 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 "Write Cache failed:". $e; Exit (); } return true; } } Get all the files in the cache Public Function List_file () { $path = $this->cache_folder; if ($handle = Opendir ($path)) { while (false!== ($file = Readdir ($handle))) { if ($file!= "." && $file!= "...") { $path 1= $path. " /". $file; if (file_exists ($path 1)) { $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!= "...") { $path 1= $path. " /". $file; if (file_exists ($path 1)) { Unlink ($path 1); } } } Closedir ($handle); } return true; } } ?> |