Home  >  Article  >  php教程  >  PHP遍历目录返回统计目录大小实例

PHP遍历目录返回统计目录大小实例

WBOY
WBOYOriginal
2016-06-13 09:34:08949browse

分享一个 PHP遍历目录并返回统计目录大小的方法。
代码:

<?<span>php 
</span><span>$dirname</span> = "test1"<span>; 
</span><span>//</span><span>mkdir($dirname);

//遍历一层目录 </span>
<span>function</span> listdir(<span>$dirname</span><span>) { 
</span><span>$ds</span> = <span>opendir</span>(<span>$dirname</span><span>); 
</span><span>while</span>(<span>$file</span> = <span>readdir</span>(<span>$ds</span><span>)) { 
</span><span>$path</span> = <span>$dirname</span>.'/'.<span>$file</span><span>; 
</span><span>if</span>(<span>is_dir</span>(<span>$file</span><span>)) { 
</span><span>echo</span> "DIR:".<span>$file</span>."<br>"<span>; 
</span><span>if</span>(<span>$file</span> != "." && <span>$file</span> != ".."<span>) { 
listdir(</span><span>$file</span><span>); 
} 
} 
</span><span>else</span><span> { 
</span><span>echo</span> "FILE:".<span>$file</span> . "<br>"<span>; 
} 
} 
}

</span><span>function</span> totdir(<span>$dirname</span>) { <span>//</span><span>对listdir稍加修改 </span>
<span>static</span> <span>$tot</span> = 0<span>; 
</span><span>$ds</span> = <span>opendir</span>(<span>$dirname</span><span>); 
</span><span>while</span>(<span>$file</span> = <span>readdir</span>(<span>$ds</span><span>)) { 
</span><span>$path</span> = <span>$dirname</span>.'/'.<span>$file</span><span>; 
</span><span>if</span>(<span>is_dir</span>(<span>$file</span><span>)) { 
</span><span>//</span><span>echo "DIR:".$file."<br>"; </span>
<span>if</span>(<span>$file</span> != "." && <span>$file</span> != ".."<span>) { 
</span><span>$tot</span> += totdir(<span>$file</span><span>); 
} 
} www</span>.jbxue.<span>com
</span><span>else</span><span> { 
</span><span>//</span><span>echo "FILE:".$file . "<br>"; </span>
<span>$tot</span> += <span>filesize</span>(<span>$path</span><span>); 
} 
}

</span><span>//</span><span>返回总计 </span>
<span>return</span> <span>$tot</span><span>; 
}

listdir(</span><span>$dirname</span><span>);

</span><span>echo</span> totdir(<span>$dirname</span>)." bytes"<span>;

</span>?>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn