Implementation code for php static caching to improve website access speed

WBOY
Release: 2016-07-25 08:59:59
Original
1243 people have browsed it
I wrote a code that uses PHP’s static cache to improve website access speed. Friends in need can refer to it.

1. The following code requirements: 1. The system supports php 2. Support file_get_contents file_put_contents [can also be replaced with a function with the same effect] 3. It is best to support gzcompress

2. How to use 1. Download the huncun.php file shared below 2. Create a folder huancun (or other) in the root directory of the website 3. Copy huncun.php to the huancun directory 4. Create a folder cache directory under the huancun directory 5. Load this file using the public file header of the website or generating a static web page header. include("/huancun/huancun.php"); 6. Clear cache

3. Disadvantages 1. Content cannot be updated in real time using this system. The cache must be cleared before the content can be updated or the content cannot be updated until the set cache time. 2. The first access speed is slower because there is no cache. The second time is to call the cache file, and it is faster then. 3. Cache files occupy disk space. It is recommended to use a server or a server with relatively large space. Or delete cache files regularly

Example,

<?php
/**
 * 清空缓存代码
 * bbs.it-home.org
*/
if($_GET['phphuancun']!="true"){
define("HC_PATH",dirname(__FILE__)."/cache/");
define("HC_TIME",1);
echo HC_getcache();exit;
}
function HC_getcache($iscache='')
{
$url="http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$cacheurl=strpos($url,"?")?$url."&phphuancun=true":$url."?phphuancun=true";
$cachename=HC_PATH.md5($url).".c";
 
$cachetime=$iscache?time()+1:time()-(HC_TIME * 60*60);
if(file_exists($cachename) && filemtime($cachename)>=$cachetime){
$return=file_get_contents($cachename);$data=function_exists(gzcompress)?@gzuncompress($return):$return;
return unserialize($data);
}else{$return=file_get_contents($cacheurl);HC_writecache($cachename,$return);return $return;}
 
}
function HC_writecache($name,$array)
{
function_exists(gzcompress)?$return =gzcompress(serialize($array)):$return=serialize($array);
@file_put_contents($name,$return);
}
?>
Copy after login


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!