Browse directory recursively and get filename

I need to make a PHP script that walks through a directory with a subdirectory. For each subdirectory (and possibly a sub-subdirectory), I need to get the filename and its parent directories.

Do you have a simple solution for this? thank

-4


source to share


2 answers


Since I had to create the same functionality for my site, I will post my function as a link.



function recursiveFileSearch($path, $searchmask = "*") {
    $path = rtrim($path, '/');

    $files = array();
    if(is_array($searchmask)) {
        for($i = 0; $i < count($searchmask); $i++) {
            $files = array_merge($files, glob($path.'/'.$searchmask[$i]));
        }
        sort($files);
    } else {
        $files = glob($path.'/'.$searchmask);
    }


    $dirs = glob($path.'/*', GLOB_ONLYDIR);
    foreach($dirs as $dir) {
        if(is_dir($dir)) {
            $files = array_merge($files, recursiveFileSearch($dir, $searchmask));
        }
    }

    sort($files);
    return $files;
}

      

+3


source


I'm not 100% sure what you are asking, but if you look at the scandir documentation , the first comment has a very useful recursive scan function.

<?php 
function dirToArray($dir) { 

      $result = array(); 

      $cdir = scandir($dir); 
      foreach ($cdir as $key => $value) 
      { 
         if (!in_array($value,array(".",".."))) 
         { 
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) 
            { 
               $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value); 
            } 
            else 
            { 
               $result[] = $value; 
            } 
         } 
      } 

      return $result; 
   } 
?> 

      



The results will be in the following format.

Array 
( 
  [subdir1] => Array 
  ( 
     [0] => file1.txt 
     [subsubdir] => Array 
     ( 
        [0] => file2.txt 
        [1] => file3.txt 
     ) 
  ) 
  [subdir2] => Array 
  ( 
   [0] => file4.txt 
  } 
)

      

+2


source







All Articles