PHP 디렉터리 순회 및 삭제 함수 예

WBOY
풀어 주다: 2016-07-25 08:59:38
원래의
930명이 탐색했습니다.
介绍一个php自定义函数,可以遍历文件夹下的文件,目录子目录,读取当前文件下目录和文件等,共三个函数,暂不支持中文。供大家学习参考。

代码如下:

<?php
/**
 * php目录遍历与删除操作
 * Edit bbs.it-home.org
*/
header("Content-type:text/html;charset=utf-8");

/**
* 读取当前目录下的文件和目录
*
* @param string $path 路径
* @return array 所有满足条件的文件
*/
function tlist($path){
$path = iconv('utf-8', 'gbk', $path);
if(!is_dir($path)){
throw new Exception($path."不是目录");
}
$arr = array('dir'=>array(),'file'=>array());
$hd = opendir($path);
while(($file = readdir($hd))!==false){
if($file=="."||$file=="..") {continue;}
if(is_dir($path."/".$file)){
$arr['dir'][] = iconv('gbk','utf-8',$file);
}else if(is_file($path."/".$file)){
$arr['file'][] = iconv('gbk','utf-8',$file);
}
}
closedir($hd);
echo "目录有:".implode("<br />",$arr['dir'])."<br />";
echo "文件有:".implode("<br />",$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) .'/'.$file;
if(is_dir($newpath)){
$arr[] = blist($path."/".$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."/".$file)){
dirDel($path."/".$file);
}else{
@unlink($path."/".$file);
}

}
closedir($hand);
@rmdir($path);
}
?>
로그인 후 복사


원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!