Home >Backend Development >PHP Tutorial >Relevant introduction to php page cache ob series functions

Relevant introduction to php page cache ob series functions

WBOY
WBOYOriginal
2016-07-25 09:08:08869browse
  1. function page_init()

  2. {
  3. $url = $_SERVER['REQUEST_URI'];//Sub-url, this parameter is generally unique
  4. $pageid = md5( $url);
  5. $dir = str_replace('/','_',substr($_SERVER['SCRIPT_NAME'],1,-4));
  6. //Directory naming method, such as exp_index
  7. if(!file_exists( $pd = PAGE_PATH.$dir.'/'))@mkdir($pd,0777) or die("$pd directory creation failed");
  8. //such as cache/page/exp_index/
  9. define('PAGE_FILE', $pd.$pageid.'.html');
  10.   //Like cache/page/exp_index/cc8ef22b405566745ed21305dd248f0e.html
  11. $contents = file_get_contents(PAGE_FILE);//Read out

  12. if( $contents && substr($contents, 13, 10) > time() )//Corresponds to the custom header added in the page_cache() function

  13. {
  14. echo substr($contents, 27);
  15. exit(0) ;
  16. }
  17. return true;
  18. }
  19. ?>

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.

  1. function page_cache($ttl = 0)
  2. {
  3. $ttl = $ttl ? $ttl : PAGE_TTL;//Cache time, default 3600s
  4. $contents = ob_get_contents();// Get content from cache
  5. $contents = "n".$contents;
  6.   //Add custom header: expired Time = generation time + cache time
  7. file_put_contents(PAGE_FILE, $contents);//Write to cache file
  8. ob_end_flush();//Release cache
  9. }
  10. ?>
Copy code

3. Function usage , pay attention to the execution order of these two functions, and don’t forget ob_start().

  1. page_init();//Page cache initialization
  2. ob_start();//Turn on cache

  3. ...//Code Section

  4. page_cache(60);//usually the last line

  5. ?>

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Get domain nameNext article:Get domain name