These days contact with the Phpcms page cache, some feelings. The benefits are not much said, it is generally used in the database query more pages, for the insertion of modified deleted page is not appropriate
The main uses of the PHP page cache are OB series functions, such as Ob_start (), Ob_end_flush (), ob_get_contents ()
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.
function Page_Init ()
{
$url = $_server[' request_uri '];//child URL, which is generally unique
$pageid = MD5 ($url);
$dir = Str_replace ('/', ' _ ', substr ($_server[' sc ript_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.
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). " --> ". $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 ()
<?php
Page_Init ();//Page Cache initialization
Ob_start ()//Open cache
..//Code Snippet
Page_cache (60);//generally the last line
?>