Home >Backend Development >PHP Tutorial >php static file cache
PHP file caching is mainly used to reduce the pressure on the database server. The static caching of PHP files mentioned here refers to static, directly generating text files such as HTML or XML, and regenerating them when there are updates, which is suitable for applications that do not change much. page.
1. Static file cache
2.Memcache, redis cache
Static cache: Use php to assemble the data, and then write the data into the file.
staticcache.php
<?php class File{ private $_dir;//定义一个默认的路径 const EXT = '.txt';//定义一个文件名后缀的常量 public function __construct(){ $this->_dir = dirname(__FILE__).'/files/';//获取文件的当前目录,再放到该目录下的files文件夹中,然后赋给$_dir } //把生成/获取/删除缓存这三个操作封装在cacheData方法中 public function cacheData($key,$value = '',$path = ''){ $filename = $this->_dir.$path.$key.self::EXT;//拼装成一个文件:默认目录、路径、文件名、文件名后缀 //将value值写入缓存 if($value !== ''){ //删除缓存 if (is_null($value)){ return @unlink($filename);//unlink删除文件,@忽略警告 } $dir = dirname($filename); if(!is_dir($dir)){//如果目录不存在就创建目录,首先要获取这个目录 mkdir($dir,0777); } return file_put_contents($filename, json_encode($value));} //获取缓存 if(!is_file($filename)){ return FALSE; }else{ return json_decode(file_get_contents($filename),true); } } }
test.php
<?php require_once('./staticcache.php'); $data = array( 'id' => 1, 'name' => 'panda', 'number' => array(1,7,8) ); $file = new File(); //获取缓存 if($file->cacheData('index_cache')){ var_dump($file->cacheData('index_cache'));exit; echo "success"; }else{ echo "error"; }
After setting the static cache time optimization:
cachetime.php
<?php class File{ private $_dir;//定义一个默认的路径 const EXT = '.txt';//定义一个文件名后缀的常量 public function __construct(){ $this->_dir = dirname(__FILE__).'/files/';//获取文件的当前目录,再放到该目录下的files文件夹中,然后赋给$_dir } //把生成/获取/删除缓存这三个操作封装在cacheData方法中 public function cacheData($key,$value = '',$cacheTime = 0){//不传cacheTime永久有效 $filename = $this->_dir.$key.self::EXT;//拼装成一个文件:默认目录、路径、文件名、文件名后缀 //将value值写入缓存 if($value !== ''){ //删除缓存 if (is_null($value)){ return @unlink($filename);//unlink删除文件,@忽略警告 } $dir = dirname($filename); if(!is_dir($dir)){//如果目录不存在就创建目录,首先要获取这个目录 mkdir($dir,0777); } $cacheTime = sprintf('%011d',$cacheTime)//规定缓存时间格式,不足11位,则前面补0,方便获取时截取 return file_put_contents($filename, $cacheTime.json_encode($value));//缓存时间与数据拼接 } //获取缓存 if(!is_file($filename)){ return FALSE; } $contents = file_get_contents($filename); $cacheTime = (int)substr($contents,0,11); $value = substr($contents,11); if($cacheTime !=0 && ($cacheTime + fileatime($filename)<time())){//判断是否过期 unlink($filename);//缓存失效删除文件 return FALSE; } return json_decode($value,true);//如果没过期,输出缓存内容 } }
Cache method to develop homepage interface
<?php require_once('./jsonxml.php'); require_once('./db.php'); require_once('./cachetime.php'); $page = isset($_GET['page']) ? $_GET['page'] : 1; $pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 6; if(!is_numeric($page)||!is_numeric($pageSize)){ return Response::show(401,'数据不合法'); } $offset = ($page - 1) * $pageSize; $sql = "select * from video where status = 1 order by orderby desc limit ".$offset.",".$pageSize; //4-4 读取缓存方式开发首页接口 $cache = new File();$videos = array(); if(!$videos = $cache->cacheData('index_yjp_cache'.$page.'-'.$pageSize)){ echo 1;exit;//如果缓存失效输出1 try{ $connect = Db::getInstance()->connect(); }catch(Exception $e){ return Response::show(403,'数据库链接失败'); } $result = mysql_query($sql,$connect); $videos = array(); while ($video = mysql_fetch_assoc($result)){ $videos[] = $video; } if($videos){ $cache->cacheData('index_yjp_cache'.$page.'-'.$pageSize,$videos,1200); } } if($videos){ return Response::show(200,'首页数据获取成功',$videos); }else{ return Response::show(400,'失败',$videos); }
Note: File cache should pay attention to the expiration time of the file
1. Get the file creation time example:
$ctime=filectime("chinawinxp.txt"); echo "创建时间:".date("Y-m-d H:i:s",$ctime);
2. Get File modification time example:
$mtime=filemtime("chinawinxp.txt"); echo "修改时间:".date("Y-m-d H:i:s",$mtime);
fileatime() function returns the last access time of the specified file
2.memcache and redis cache
Enable service; connection port, cache server ; PHP operation PHP operation redis, mencache conditions:
1) Install phpredis extension/mencache extension
2) PHP connect redis service connet(127.0.0.1,6379);
Connect mencache service connet('memcache_host' ,11211);
3) set set cache
4) get get cache
Set cache time: set key time (time) value
PHP cache includes PHP compilation cache and There are two types of PHP data caching. PHP is an interpreted language that compiles and runs at the same time. The advantage of this operating mode is that program modification is very convenient, but the operating efficiency is very low. The PHP compilation cache has been improved to deal with this situation, so that the PHP language can cache the compilation results of the program as long as it is run once. In this way, every subsequent run does not need to be compiled again, which greatly improves the running speed of PHP.
Related recommendations:
implementation code for php static cache to improve website access speed
ThinkPHP static cache update problem
thinkphp static cache usage analysis, thinkphp static cache_PHP tutorial
The above is the detailed content of php static file cache. For more information, please follow other related articles on the PHP Chinese website!