很多的開(kāi)源cms系統(tǒng)都有一鍵清除緩存的功能,緩存是為了減輕服務(wù)器的壓力而產(chǎn)生的,但是同時(shí)有緩存的存在也可能使一些數(shù)據(jù)不能實(shí)時(shí)更新,對(duì)此,我們就來(lái)實(shí)現(xiàn)一個(gè)ThinkPHP的清理緩存的功能。代碼如下:
ThinkPHP后臺(tái)執(zhí)行的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
//獲取要清楚的目錄和目錄所在的絕對(duì)路徑 public function cache(){ ////前臺(tái)用ajax get方式進(jìn)行提交的,這里是先判斷一下 if ( $_POST [ 'type' ]){ //得到傳遞過(guò)來(lái)的值 $type = $_POST [ 'type' ]; //將傳遞過(guò)來(lái)的值進(jìn)行切割,我是用“-”進(jìn)行切割的 $name = explode ( '-' , $type ); //得到切割的條數(shù),便于下面循環(huán) $count = count ( $name ); //循環(huán)調(diào)用上面的方法 for ( $i =0; $i < $count ; $i ++){ //得到文件的絕對(duì)路徑 $abs_dir =dirname(dirname(dirname(dirname( __FILE__ )))); //組合路徑 $pa = $abs_dir . 'indexRuntime' ; $runtime = $abs_dir . 'indexRuntime~runtime.php' ; if ( file_exists ( $runtime )) //判斷 文件是否存在 { unlink( $runtime ); //進(jìn)行文件刪除 } //調(diào)用刪除文件夾下所有文件的方法 $this ->rmFile( $pa , $name [ $i ]); } //給出提示信息 $this ->ajaxReturn(1, '清除成功' ,1); } else { $this ->display(); } } public function rmFile( $path , $fileName ){ //刪除執(zhí)行的方法 //去除空格 $path = preg_replace( '/(/){2,}|{}{1,}/' , '/' , $path ); //得到完整目錄 $path .= $fileName ; //判斷此文件是否為一個(gè)文件目錄 if ( is_dir ( $path )){ //打開(kāi)文件 if ( $dh = opendir( $path )){ //遍歷文件目錄名稱 while (( $file = readdir( $dh )) != false){ //逐一進(jìn)行刪除 unlink( $path . '' . $file ); } //關(guān)閉文件 closedir ( $dh ); } } } |
前臺(tái)頁(yè)面部分代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
< script type = "text/javascript" src = "__PUBLIC__/admin/js/jquery.js" ></ script > < script type = "test/javascript" > $(function(){ $('#button').click(function(){ if(confirm("確認(rèn)要清除緩存?")){ var $type=$('#type').val(); var $mess=$('#mess'); $.post('__URL__/clear',{type:$type},function(data){ alert("緩存清理成功"); }); }else{ return false; } }); }); </ script > |