/**
* 遍历文件夹
*/
function Tree($space='',$dir="./")
{
//建立dir对象
$d = dir($dir);
//得到子级文件及文件夹总数
$sonSum=count(scandir($dir));
while (false !== ($entry = $d->read()))
{
$sonSum--;
//判断是否为最后一个,输出对应的树杈
$list=$sonSum?"├":"└";
//去掉两个默认的目录
if($entry=='..' or $entry=='.')
continue;
//页面是utf-8的,系统是winXP,所以需要将文件名进行转码
echo $space.$list.iconv('gb2312','utf-8',$entry)."
\n";
//输出当前目录/文件
$currentPath=$d->path.'/'.$entry;
//如果是目录则遍历这个目录
if(is_dir(realpath($currentPath)))
//调用函数本身
Tree($space.($sonSum?'│':'').' ',$currentPath);
}
$d->close();
}
Tree(); |
当然上面的代码只是生成一个类似ms-dos中的tree /all命令生成的树状目录结构。
去掉显示树杈的部分就可以投入生产了。
去掉显示树杈代码后如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | /**
* 遍历文件夹
*/
function Tree($dir="./")
{
$d = dir($dir);
while (false !== ($entry = $d->read()))
{
if($entry=='..' or $entry=='.')
continue;
echo $space.$list.iconv('gb2312','utf-8',$entry)."
\n";
$currentPath=$d->path.'/'.$entry;
if(is_dir(realpath($currentPath)))
Tree($currentPath);
}
$d->close();
}
Tree(); |
递归遍历文件夹,并计算文件夹大小的代码是:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | function dirsize($dir) {
@$dh = opendir($dir);
$size = 0;
while ($file = @readdir($dh)) {
if ($file != "." and $file != "..") {
$path = $dir."/".$file;
if (is_dir($path)) {
$size += dirsize($path);
} elseif (is_file($path)) {
$size += filesize($path);
}
}
}
@closedir($dh);
return $size;
} |