Introduction to the php page caching ob series of functions

  • 2020-05-26 08:01:37
  • OfStack

Here's caching technology brief introduction: https: / / www ofstack. com article / 4965. htm

php page caching mainly USES the ob series of functions, such as ob_start(),ob_end_flush(),ob_get_contents()

Below is the coding section.

1. Initialization function, 1 is to set the page cache path, cache file naming format, etc., can be customized according to personal preferences. The identification ID used here is the encrypted $_SERVER[REQUEST_URI] parameter. There is also 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.

 
function page_init() 
{ 
$url = $_SERVER['REQUEST_URI'];// The child url , this parameter 1 As is the only 1 the  
$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',$pd.$pageid.'.html'); 
  // Such as cache/page/exp_index/cc8ef22b405566745ed21305dd248f0e.html 
$contents = file_get_contents(PAGE_FILE);// read  

if($contents && substr($contents, 13, 10) > time() )// The corresponding page_cache() The custom header added to the function  
{ 
echo substr($contents, 27); 
exit(0); 
} 
return true; 
} 


2. Page cache function, which USES a trick: add a header to the contents of the cache file -- the expiration time, so you only need to compare the expiration time in the header with the current time each time (in the page_init() function) to determine whether the cache has expired.
 
function page_cache($ttl = 0) 
{ 
$ttl = $ttl ? $ttl : PAGE_TTL;// Cache time, default 3600s 
$contents = ob_get_contents();// Get the content from the cache  
$contents = "<!--page_ttl:".(time() + $ttl)."-->\n".$contents; 
  // Add custom header: expiration time = To generate the time + Cache time  
file_put_contents(PAGE_FILE, $contents);// Write to the cache file  
ob_end_flush();// Release the cache  
} 

3. Function use, notice that the two functions are executed in sequence, and don't forget ob_start()
 
<?php 
page_init();// Page cache initialization  
ob_start();// Open the cache  

...// Code segment  

page_cache(60);//1 As is the last 1 line  

?> 


Related articles: