A
A
Apexis2018-05-16 19:23:16
PHP
Apexis, 2018-05-16 19:23:16

How to create tree of files and folders recursively?

The code below creates a list of files and folders. How to create a tree with unlimited nesting?

public static function getFiles($startDir) 
  {
    $files = [];
    if($handle = opendir($startDir)) {
      while (false !== ($i = readdir($handle))) {
        if (is_dir($startDir . DIRECTORY_SEPARATOR . $i)) {
          if (!in_array($i, ['.', '..', 'purity'])) {
            $files[$i] = Purity::getFiles($startDir . DIRECTORY_SEPARATOR . $i);
          }
        } elseif (!in_array(pathinfo($i, PATHINFO_EXTENSION), ['dat', 'htaccess', 'txt'])) {
          $files[] = $startDir . DIRECTORY_SEPARATOR . $i;
        }
      }
      closedir($handle);
    }
    return $files;
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2018-05-16
@miraage

Learn SPL: RecursiveIteratorIterator + RecursiveDirectoryIterator.
Examples / Brief description: https://stackoverflow.com/a/12236744/790304

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question