-
-
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');
- //Like cache/page/exp_index/cc8ef22b405566745ed21305dd248f0e.html
- $contents = file_get_contents(PAGE_FILE);//Read out
if( $contents && substr($contents, 13, 10) > time() )//Corresponds to the custom header added in the page_cache() function
- {
- echo substr($contents, 27);
- exit(0) ;
- }
- return true;
- }
- ?>
-
Copy code
Second, page caching function, a trick is used here: add a header to the content of the cache file Information - expiration time, so each time you only need to compare the expiration time in the header with the current time (conducted 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 content from cache
- $contents = "n".$contents;
- //Add custom header: expired Time = generation time + cache time
- file_put_contents(PAGE_FILE, $contents);//Write to cache file
- ob_end_flush();//Release cache
- }
- ?>
Copy code
3. Function usage , pay attention to the execution order of these two functions, and don’t forget ob_start().
-
-
- page_init();//Page cache initialization
- ob_start();//Turn on cache
...//Code Section
page_cache(60);//usually the last line
- ?>
-
Copy code
|