background image

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

介绍一个

php 自定义函数,可以遍历文件夹下的文件,目录子目录,读取当前文件下目录和

文件等,共三个函数,暂不支持中文。供大家学习参考。
代码如下:

<?php
/**
 * php 目录遍历与删除操作
 * Edit www.jbxue.com
*/
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 所有满足条件的文件