phpdirectory-listing

Exclude folders from recursion in recursive directory iterator php


I need to exclude all files and folders from a certain directories while doing the recursion. I have this code so far :

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($websiteRoot.$file["filepathfromroot"]));
     foreach ($it as $currentfile)
     {
      if (!$it->isDot()&&$it->isFile()&&!in_array($it->getSubPath(), $file["exclude-directories"])) {

        //do something
         }
     }

However this subpath will only match for children and and not files and sub directories off the children. i.e For a directory structure of Foo/bar/hello.php. If you add Foo to the exclude list hello.php would still come in the result.

Does anyone have a solution for this ?


Solution

  • Replace :

    in_array($it->getSubPath(), $file["exclude-directories"])
    

    By something like :

    !in_array_beginning_with($it->getSubPath(), $file["exclude-directories"])
    

    And you implement the function :

    function in_array_beginning_with($path, $array) {
      foreach ($array as $begin) {
        if (strncmp($path, $begin, strlen($begin)) == 0) {
          return true;
        }
      }
      return false;
    }
    

    But that's not a very good way because you will recursivly get into useless directories even if they are very big and deep. In your case, I'll suggest you to do a old-school recursive function to read your directory :

    <?php
    
    function directory_reader($dir, array $ignore = array (), array $deeps = array ())
    {
        array_push($deeps, $dir);
        $fulldir = implode("/", $deeps) . "/";
        if (is_dir($fulldir))
        {
            if (($dh = opendir($fulldir)) !== false)
            {
                while (($file = readdir($dh)) !== false)
                {
                    $fullpath = $fulldir . $file;
                    if (in_array($fullpath, $ignore)) {
                        continue ;
                    }
    
                    // do something with fullpath
                    echo $fullpath . "<br/>";
    
                    if (is_dir($fullpath) && (strcmp($file, '.') != 0) && (strcmp($file, '..') != 0))
                    {
                        directory_reader($file, $ignore, $deeps);
                    }
                }
                closedir($dh);
            }
        }
        array_pop($deeps);
    }
    

    If you try directory_reader(".", array("aDirectoryToIngore")), it will not be read at all.