前言
thinkPHP的缓存功能对于网站运行来说是比不可少的,但是在有些时候,特别是在做开发的时候,缓存实在是令人头疼,这边文章分享下tp5通过ajax提交达到一键清除网站缓存的功能
使用方法
后端PHP中
在公共文件
common.php
中添加公共方法if (!function_exists('delete_dir_file')) { /** * 循环删除目录和文件 * @param string $dir_name * @return bool */ function delete_dir_file($dir_name) { $result = false; if(is_dir($dir_name)){ if ($handle = opendir($dir_name)) { while (false !== ($item = readdir($handle))) { if ($item != '.' && $item != '..') { if (is_dir($dir_name . DS . $item)) { delete_dir_file($dir_name . DS . $item); } else { unlink($dir_name . DS . $item); } } } closedir($handle); if (rmdir($dir_name)) { $result = true; } } } return $result; } }
在
controller(控制器)
中添加/** * 清除缓存 */ public function clear() { if (delete_dir_file(CACHE_PATH) || delete_dir_file(TEMP_PATH)) { $this->success('清除缓存成功!'); } else { $this->error('清除缓存失败!'); } }
- 在
JavaScript
中添加
<script type="text/javascript">
//清除缓存
function clearPhp(obj) {
var url=obj.getAttribute('data-GetUrl');
//询问框
layer.confirm('你确定要清除缓存吗?', {icon: 3, title:'提示'},
function(){
$.get(url,function(info){
if(info.code === 1){
setTimeout(function () {location.href = info.url;}, 1000);
}
layer.msg(info.msg,{icon:1});
});
},
function(){});
}
</script>
在
html页面
中,因为需要在任何页面都能快速清除缓存,所以我把调用代码写在了公共文件中<a href="javascript:void(0);" class="list-group-item cache" onclick="clearPhp(this)" data-GetUrl="{:url('admin/clear')}"> <div class="media"> <div class="media-img" style="color: #333;"><i class="fa fa-bolt"></i></div> <div class="media-body"> <div class="font-strong"></div>清除所有缓存<small class="text-muted float-right">删除所有 temp+cache</small> </div> </div> </a>
这样下来就能达到一键清除系统缓存的目的了
评论 (0)