php 目录遍历与删除的函数示例

原创
2016-07-25 08:59:38 640浏览
介绍一个php自定义函数,可以遍历文件夹下的文件,目录子目录,读取当前文件下目录和文件等,共三个函数,暂不支持中文。供大家学习参考。

代码如下:

array(),'file'=>array());
$hd = opendir($path);
while(($file = readdir($hd))!==false){
if($file=="."||$file=="..") {continue;}
if(is_dir($path."//m.sbmmt.com/m/".$file)){
$arr['dir'][] = iconv('gbk','utf-8',$file);
}else if(is_file($path."//m.sbmmt.com/m/".$file)){
$arr['file'][] = iconv('gbk','utf-8',$file);
}
}
closedir($hd);
echo "目录有:".implode("
",$arr['dir'])."
"; echo "文件有:".implode("
",$arr['file']); } /** * 遍历当前目录下的文件和目录以及子文件夹中目录 * * @param string $path 路径 * @return array 所有满足条件的文件 */ function blist($path){ if(!is_dir(iconv("utf-8","gbk",$path))){ throw new Exception("文件夹".$path."不存在或者不是文件"); } $arr = array(); $hd = opendir(iconv("utf-8","gbk",$path)); while(($file = readdir($hd))!==false){ if($file=="."||$file=="..") {continue;} $newpath=iconv('utf-8', 'gbk', $path) .'//m.sbmmt.com/m/'.$file; if(is_dir($newpath)){ $arr[] = blist($path."//m.sbmmt.com/m/".$file); }else if(is_file($newpath)){ $arr[] = iconv('gbk','utf-8',$file); } } closedir($hd); return $arr; } /** * 删除目录下的文件以及子目录 * #param string $path 路径 * #return string 删除成功返回true 失败返回false; */ function dirDel($path){ if(!is_dir($path)){ throw new Exception($path."输入的不是有效目录"); } $hand = opendir($path); while(($file = readdir($hand))!==false){ if($file=="."||$file=="..") continue; if(is_dir($path."//m.sbmmt.com/m/".$file)){ dirDel($path."//m.sbmmt.com/m/".$file); }else{ @unlink($path."//m.sbmmt.com/m/".$file); } } closedir($hand); @rmdir($path); } ?>


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。