Home >Backend Development >PHP Tutorial >PHP traverses all directories and files under the specified path (example)

PHP traverses all directories and files under the specified path (example)

WBOY
WBOYOriginal
2016-07-25 08:55:101272browse
  1. /**
  2. * php traverse directories and files
  3. * by bbs.it-home.org
  4. */
  5. function scan_all($dir){
  6. $temp = scandir($dir);
  7. if(is_array($temp) && count($temp)>2){
  8. array_shift($temp);
  9. array_shift($temp);
  10. foreach($temp as $v){
  11. $cur_dir=$dir.DIRECTORY_SEPARATOR.$v;
  12. if(is_dir($cur_dir)){
  13. echo $v." =>";
  14. echo "
    ";
  15. scan_all($cur_dir);
  16. echo "";
  17. }else if(is_file($cur_dir)){
  18. echo "FILE:".$v."
    ";
  19. }else{
  20. echo 'err';
  21. }
  22. }
  23. }
  24. }
  25. $dir = "D:/yourdir/";
  26. scan_all($dir);
复制代码

方法2,DirectoryIterator:

  1. /**

  2. * php traverse directories and files
  3. * by bbs.it-home.org
  4. */
  5. function directoryiterator($path)
  6. {
  7. $iterator = new DirectoryIterator($path);

  8. foreach ($iterator as $fileinfo) {

  9. if(!$fileinfo->isDot())
  10. {
  11. if($fileinfo->isDir())
  12. {
  13. echo $fileinfo.'=>
    ';
  14. directoryiterator($path.DIRECTORY_SEPARATOR.$fileinfo);
  15. echo '';
  16. }
  17. else
  18. {
  19. echo $fileinfo->getFilename().'
    ';
  20. }
  21. }
  22. }
  23. }
  24. $dir = "D:/yourdir/";
  25. directoryiterator($dir);

复制代码


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