thinkphp清除缓存方法

php thinkphp php 2090      收藏
thinkphp运行久了,会产生很多缓存文件,占用服务器资源,本文介绍清除缓存文件的方法。

thinkphp运行久了,会产生很多缓存文件,占用服务器资源,本文介绍清除缓存文件的方法。

具体实施的思路是:

1、在入口文件或者配置文件中,定义缓存文件路径(也可以直接在方法中定义好路径)

2、在Action中,使用快捷方法C方法将缓存路径引入Action中(在方法中直接定义则不需要使用C方法)

3、在网站后台模板页面,添加清除缓存按钮,链接指向Action类中的清除缓存方法

4、在该清除方法中定义删除函数或者引入外部删除缓存函数,执行删除缓存功能


thinkphp的缓存文件分为前后台,删除时需要分别定义前台删除方法和后台删除方法。

本文参考了网上其他人的方法,做了一下总结。具体方法是单独定义了一个缓存管理类文件,然后在类中定义两个方法,分别是前台删除方法和后台删除方法,以及缓存文件删除方法。


自学php博客


自学php博客

自学php博客


代码是:

//清空缓存方法

public function rmdirr($dirname) {

if (!file_exists($dirname)) {

return false;

}

if (is_file($dirname) || is_link($dirname)) {

return unlink($dirname);

}

$dir = dir($dirname);

if($dir){

while (false !== $entry = $dir->read()) {

if ($entry == '.' || $entry == '..') {

continue;

}

//递归

$this->rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);

}

}

$dir->close();

return rmdir($dirname);

}

//前台页面

public function home(){

//清文件缓存

$dirs = array('Home/Runtime/Cache');

@mkdir('Home/Runtime/Cache',0777,true);

//清理缓存

foreach($dirs as $value) {

$this->rmdirr($value);

}

//echo '<div >系统缓存清除成功!</div>';  

$res=true;

echo json_encode($res);

}

//后台页面

public function admin(){

//清文件缓存

$dirs = array('MAdmin/Runtime/Cache');

@mkdir('MAdmin/Runtime/Cache',0777,true);

//清理缓存

foreach($dirs as $value) {

$this->rmdirr($value);

}

//echo '<div >系统缓存清除成功!</div>'; 

$res=true;

echo json_encode($res);

}