Home > Article > Backend Development > How to use php code to delete folders and clear cache instances?
Let’s take a look at the deletion code first:
<?php header('content-type:text/html;charset=utf-8'); function delFile($fpath) { $filesize = array(); $filepath = iconv('gb2312', 'utf-8', $fpath); if (is_dir($fpath)) { if ($dh = opendir($fpath)) { while (($file = readdir($dh)) !== false) { if($file != '.' && $file != '..') { $filesize[] = delFile($fpath.'/'.$file); } } closedir($dh); } /* * 方便统计目录数 */ $filesize['file'] = 0; if(@rmdir($fpath) === true) { echo "{$filepath}................删除成功<br>\n"; } else { echo "{$filepath}................删除失败<br>\n"; } } else { if(is_file($fpath)) { $filesize[] = $fsize = filesize($fpath); if(@unlink($fpath) === true) { echo "{$filepath}...{$fsize}K................删除成功<br>\n"; } else { echo "{$filepath}...{$fsize}K................删除失败<br>\n"; } } } return $filesize; } /* * function getArrSum(array &$arr) 数组求和 * array &$arr 被处理数组 */ function getArrSum(&$arr) { if(is_array($arr)) { foreach ($arr as &$value) { $value = getArrSum($value); } return array_sum($arr); } else { return $arr; } } $fpath = 'D:/test'; $filesize = delFile($fpath); $size = getArrSum($filesize); printf('为您节省:%.3fM 空间', $size/(1024*1024)); ?>
A simple PHP test code for regularly cleaning files in a folder:
<?php ignore_user_abort(); //客户端断开时,可以让脚本继续在后台执行 set_time_limit(0); //忽略php.ini设置的脚本运行时间限制 $interval = 5*60; //设置执行周期,单位为秒,5分钟为 5*60=300 do{ $dir = "temp/"; //你的临时目录位置 $handle=opendir("{$dir}/"); while (false !== ($file=readdir($handle))) { if ($file!="." && $file!=".." && !is_dir("{$dir}/{$file}")) { @unlink ("{$dir}/{$file}"); } } closedir($handle); //关闭由 opendir() 函数打开的目录 sleep($interval); //执行一个周期后,休眠$interval时间,休眠结束后脚本继续执行 }while(true); //周期性执行脚本
Create a flag.txt file and enter 1 or 0 in it , "0" means to stop execution, "1" means to continue execution. This way it can be started and stopped.
<?php $flag = 1; //将执行标志设置为1,默认为执行 ignore_user_abort(); //客户端断开时,可以让脚本继续在后台执行 set_time_limit(0); //忽略php.ini设置的脚本运行时间限制 $interval = 5*60; //设置执行周期,单位为秒,5分钟为 5*60=300 do{ $flagfile = "flag.txt"; //标志放置在文件“flag.txt”中。“0”表示停止执行,“1”表示继续执行 if(file_exists($flagfile) && is_readable($flagfile)) { //读取文件内容 $fh = fopen($flagfile,"r"); while (!feof($fh)) { $flag = fgets($fh); //存储标志 } fclose($fh); } $dir = "temp/"; //你的临时目录位置 $handle=opendir("{$dir}/"); while (false !== ($file=readdir($handle))) { if ($file!="." && $file!=".." && !is_dir("{$dir}/{$file}")) { @unlink ("{$dir}/{$file}"); } } closedir($handle); //关闭由 opendir() 函数打开的目录 sleep($interval); //执行一个周期后,休眠$interval时间,休眠结束后脚本继续执行 }while($flag);
The above is the detailed content of How to use php code to delete folders and clear cache instances?. For more information, please follow other related articles on the PHP Chinese website!