提示:谨慎操作,因为删除的文件不会进入回收站!
header("Content-type: text/html;charset=utf-8");
error_reporting(E_ALL ^E_NOTICE^E_WARNING);
//从文件夹里删除指定后缀的文件
class delFileByExt{
private $delfile_arr=array('xls');//要删除的文件格式
static $num=0;
static $del_num=0;
static $delog=array();
public $dir;
function __construct($dir)
{
$this->dir=$dir;
}
public function read_all($dir){
if(!is_dir($dir)){
return false;
}
$handle = opendir($dir);
if($handle){
while(($fl = readdir($handle)) !== false){
$temp = $dir.DIRECTORY_SEPARATOR.$fl;
//如果不加 $fl!='.' && $fl != '..' 则会造成把$dir的父级目录也读取出来
if(is_dir($temp) && $fl!='.' && $fl != '..'){
echo '目录:'.$temp.'<br>';
$this->read_all($temp);
}else{
if($fl!='.' && $fl != '..'){
if($temp){
self::$num++;
$arr_path=explode('.',$temp);
$ext=end($arr_path);
echo '---文件:'.$temp.'<br>';
if(in_array($ext,$this->delfile_arr)){
$return_state=unlink($temp);
if($return_state){
echo '<b style="color:red;">---已删除:'.$temp.'</b><br>';
self::$del_num++;
if(empty(self::$delog[$ext])){
self::$delog[$ext]=1;
}else{
self::$delog[$ext]+=1;
}
}
}
}
}
}
}
}
}
//统计文件总数
public function countNum(){
echo '该文件夹:'.$this->dir.'统计如下:';
echo '--一共有'.self::$num.'个文件!<br>';
echo '----其中有'.self::$del_num.'个后缀为'.join(',',$this->delfile_arr).'的文件已经被删除!<br>';
foreach (self::$delog as $k=>$v){
echo '------包含有'.$v.'个文件 '.$k.' 格式的文件!<br>';
}
}
}
//使用
$obj=new delFileByExt('D:\PROJECT\jysx_single\public\file\upload\2015-07\15');
$obj->read_all($obj->dir);
$obj->countNum();