Home > Article > Backend Development > Introduction to php page cache ob series functions
PHP page caching mainly uses the ob series of functions, such as ob_start(), ob_end_flush(), ob_get_contents()
The following is the encoding part.
1. Initialization function, usually setting the page cache path, cache file naming format, etc., which can be customized according to personal preferences. The identification ID used here is the encrypted $_SERVER[REQUEST_URI] parameter. There is an if judgment at the end of this function: if the cache period has not passed, load the cache file, otherwise load the source file.
Copy code The code is as follows:
function page_init()
{
$url = $_SERVER['REQUEST_URI'];//Sub-url, this parameter is generally unique
$pageid = md5($url);
$dir = str_replace('/','_',substr($_SERVER['SCRIPT_NAME'],1,-4));
//Directory naming method, 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, 13, 10) > time () )//Corresponding to the custom header added in the page_cache() function
{
echo substr($contents, 27);
exit(0);
}
return true;
}
2. Page Cache function, here uses a trick: add a header information - expiration time to the content of the cache file, so each time you only need to compare the expiration time in the header with the current time (in the page_init() function Perform) to determine whether the cache has expired.
Copy code The code is as follows:
function page_cache($ttl = 0)
{
$ttl = $ttl ? $ttl : PAGE_TTL;//Cache time, default 3600s
$contents = ob_get_contents();//Get from cache Content
$contents = "n".$contents;
//Add custom header: expiration time = generation time +Cache time
file_put_contents(PAGE_FILE, $contents);//Write into the cache file
ob_end_flush();//Release the cache
}
3. Function usage, please note that these two functions have execution order, and there are other Forgot ob_start()
Copy the code The code is as follows:
page_init();//Page cache initialization
ob_start();//Turn on the cache
...//Code segment
page_cache(60) ;//Usually the last line
?>