Home >Backend Development >PHP Tutorial >PHP简略递归遍历所有目录

PHP简略递归遍历所有目录

WBOY
WBOYOriginal
2016-06-13 12:15:111101browse

PHP简单递归遍历所有目录

博主热衷各种互联网技术,常啰嗦,时常伴有强迫症,常更新,觉得文章对你有帮助的可以关注我。 转载请注明"深蓝的镰刀"


function list_dir($root){    $dirs = scandir($root);    foreach($dirs as $dir){        if(is_dir($root.DIRECTORY_SEPARATOR.$dir) && (in_array($dir,array('.','..')) != '.')){            echo $root.DIRECTORY_SEPARATOR.$dir.PHP_EOL;            list_dir($root.DIRECTORY_SEPARATOR.$dir);        }    }}list_dir('.');


值得注意的几点:

1.递归一定要有跳出的条件,否则就是无限循环

2.使用常量DIRECTORY_SEPARATOR替代 "/"可以兼容linux和windows的不同目录分隔符

3.使用is_array($dir,array('.','..')) != '.',而不是substr($dir,0,1) != '.' 是因为linux里面很多隐藏目录都是以"."开头的

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