Home  >  Article  >  Backend Development  >  A small cache class in PHP_PHP tutorial

A small cache class in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:37:52701browse

The function is very simple, it is to cache the entire page, you can set the cache time, and you can cache a specific URL, for example: test.php?id=12. When the target file is updated, such as test.php, the cache file will also be updated. , even if it is still within the cache period.

class cache
{
var $cache_dir = ./cache/;//This is the directory where the cache files will be stored;
var $cache_time = 120;//How much time will keep the cache files in seconds.

var $caching = false;
var $file = ;

function cache()
{
//Constructor of the class
$this->file = $this->cache_dir . urlencode( $_SERVER[REQUEST_URI] );
if(file_exists($this->file)) $expired = $this->check_expire();
else $expired = false;
if ( file_exists ( $this->file ) && ( filemtime ( $this->file ) + $this->cache_time ) > time() && !$expired )
{
//Grab the cache:
$handle = fopen( $this->file , "r");
do {
$data = fread($handle, 8192);
if (strlen($data) == 0) {
break;
}
echo $data;
} while (true);
fclose($handle);
exit();
}
else
{
//create cache :
$this->caching = true;
ob_start();
$now = time();
echo " ";
}
}

function close()
{
//You should have this at the end of each page
if ( $this->caching )
{
//You were caching the contents so display them, and write the cache file
$data = ob_get_clean();
echo $data;
$fp = fopen( $this->file , w );
fwrite ( $fp , $data );
fclose ( $fp );
}
}
function check_expire(){
$fp = fopen($this->file,"r");
preg_match("/:([d]+)-/",fread($fp,200),$time);
$modify_time = $time[1];
if($modify_time return true;
}
else{
return false;
}

}
}


Usage:

//Example :
$ch = new cache();
echo date("D M j G:i:s T Y");
$ch->close();

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486516.htmlTechArticleThe function is very simple, it is to cache the entire page, you can set the cache time, and you can cache specific URLs, such as: test .php?id=12, when the target file is updated, such as test.php, the cache file will also...
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