PHP Page Caching method Summary _php Tips

Source: Internet
Author: User
Tags md5 mkdir sha1

This article summarizes the PHP page caching method. Share to everyone for your reference. The specific analysis is as follows:

The main use of the PHP page cache is the OB series functions, such as Ob_start (), Ob_end_flush (), ob_get_contents (), but the more advanced caching is not using these functions, this article will give an example to illustrate the end.

Let's take a look at the caching commonly used OB series functions:

Ob_start (): the flag of page cache start, the content of this function until Ob_end_flush () or Ob_end_clean () is saved in the page cache;

ob_get_contents (): used to get the contents of the page cache, to get to the future, we can think how to deal with these content is all right, filter the field, matching content, can ~ ~ ~

Ob_end_flush (): indicates the end of the page cache, and I verified that the cached content will be output to the current page, that is, the cached content can be displayed.

With this three PHP functions, you can achieve a powerful function, if the database query volume is large, you can use the cache to solve this problem.

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, this function finally has an if judge, if not over the cache period, then load the cache file, Otherwise load the source file, the code is as follows:

Copy Code code as follows:
function Page_Init ()
{
$url = $_server[' request_uri '];//child URL, which is generally unique
$pageid = MD5 ($url);
$dir = Str_replace ('/', ' _ ', substr ($_server[' script_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 function, here is a trick to 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, you can determine whether the cache expires, the code is as follows:
Copy Code code as follows:
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). " -->n ". $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 also do not forget the Ob_start (), the code is as follows:
Copy Code code as follows:
<?php
Page_Init ();//Page Cache initialization
Ob_start ()//Open cache

..//Code Snippet

Page_cache (60);//generally the last line

?>

Example 2, here is an example to illustrate the PHP page caching technology, the following code:
Copy Code code as follows:
<?php
$_time = 10;
$dir = "D:\php\";

function Cache_start ($_time, $dir)
{
$cachefile = $dir. '/' SHA1 ($_server[' Request_uri '). HTML ';
$cachetime = $_time;
Ob_start ();
if (file_exists ($cachefile) && (Time ()-filemtime ($cachefile) < $cachetime))
{
Include ($cachefile);
Ob_end_flush ();
Exit
}
}

function Cache_end ($dir)
{
$cachefile = $dir. '/' SHA1 ($_server[' Request_uri '). HTML ';
$fp = fopen ($cachefile, ' w ');
Fwrite ($FP, ob_get_contents ());
Fclose ($FP);
Ob_end_flush ();
}

Cache_start ($_time, $dir);
Here is the output, placed between the Cache_start and Cache_end two methods
For ($i =0 $i <5; $i + +)
{
echo $i;
Sleep (1);
}
Cache_end ($dir);
?>

For example, use the makefile as a caching code as follows:
Copy Code code as follows:
<?php
Ob_start ();
/**
* @author He Nihui
* @copyright 2009-3-13
* @param string $cache _folder Slow folder
* @param int $cache _create_time File cache time
* @example $cache =new esj_cache ('./_cache ', 100)
* @example $cache->read_cache () read cache and output
* @example $cache->creatre_cache () to create a cached file (placed at the end of the file)
* @example $cache->list_file () returns a list of all cached files
* @example $cache->del_file () Delete all cached files
*/

Class esj_cache{
Private $cache _folder=null;//cacher Folder
Private $wroot _dir=null;//Site Directory
Private $cacher _create_time=null;//cacher File creation time

Public function __construct ($cache _foldername, $cacher _time=100)
{
Ob_start ();
$this->wroot_dir=$_server[' Document_root '];
$this->cache_folder= $cache _foldername;
$this->cacher_create_time= $cacher _time;
}

Public Function Read_cache ()
{
try {
if (Self::create_folder ($this->cache_folder))
{
Self::get_cache ()//output cache file information
}else
{
echo "Cache folder creation failed!";
return false;
}

}catch (Exception $e) {
Echo $e;
return false;
}
}

Test whether the cached folder exists
Private Function Exist_folder ($foler)
{
if (file_exists ($this->wroot_dir.) /". $foler)) {
return true;
}else {
return false;
}
}

Create a new Folder
Private Function Create_folder ($foler)
{
if (!self::exist_folder ($foler))
{
try{
mkdir ($this->wroot_dir.) /". $foler, 0777);
chmod ($this->wroot_dir.) /". $foler, 0777);
return true;
}catch (Exception $e)
{
Self::get_cache ()//output cache
return false;
}
return false;
}
Else
{
return true;
}
}

Reading cached files
Private Function Get_cache ()
{
$file _name=self::get_filename ();
if (file_exists ($file _name) && ((Filemtime ($file _name) + $this->cacher_create_time) > Time ())
{
$content =file_get_contents ($file _name);
if ($content)
{
Echo $content;
Ob_end_flush ();
Exit
}else
{
echo "file read failed";
Exit

}

}
}

Returns the name of the file
Private Function Get_filename ()
{
$filename = $file _name= $this->wroot_dir. '/'. $this->cache_folder. ' /'. MD5 ($_server[' query_string '). ". HTML ";
return $filename;
}

Create a cached file
Public Function Create_cache ()
{
$filename =self::get_filename ();
if ($filename!= "")
{
try{
File_put_contents ($filename, ob_get_contents ());
return true;
}catch (Exception $e)
{
echo "Write Cache failed:". $e;
Exit ();
}
return true;
}
}

Get all the files in the cache
Public Function List_file ()
{
$path = $this->cache_folder;
if ($handle = Opendir ($path)) {
while (false!== ($file = Readdir ($handle))) {
if ($file!= "." && $file!= "...") {
$path 1= $path. " /". $file;
if (file_exists ($path 1))
{
$result []= $file;
}
}
}
Closedir ($handle);
}
return $result;
}

Delete all files in the cache
Public Function Del_file ()
{
$path = $this->cache_folder;
if ($handle = Opendir ($path)) {
while (false!== ($file = Readdir ($handle))) {
if ($file!= "." && $file!= "...") {
$path 1= $path. " /". $file;
if (file_exists ($path 1))
{
Unlink ($path 1);
}
}
}
Closedir ($handle);
}
return true;
}

}

?>

I hope this article will help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.