0

I need to get only the folder names in a directory. So far I found the DirectoryIterator to be useful. However I am not getting the desired names of the folders.

$dir = new DirectoryIterator(dirname($directory));
foreach ($dir as $fileinfo) {

    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
        if ($fileinfo->isDir()) {
        //echo $fileinfo->getFilename() . '<br>';
        }    
    }    
}

Please see: I also want to skip the dots (.) and (..) while having the ability to ignore folders I choose.

Nik
  • 139
  • 2
  • 14
  • Possible duplicate of [PHP script to loop through all of the files in a directory?](http://stackoverflow.com/questions/4202175/php-script-to-loop-through-all-of-the-files-in-a-directory) – Rein Jan 23 '16 at 09:53
  • doesn't `!$fileinfo->isDot()` already skip the `.` and `..` ?? – Andrew Jan 23 '16 at 10:43
  • @Andrew Yes, that part is intentional. It's part of my solution. However as a whole it does not seem to work. Anyway I have come up with an alternate solution below. – Nik Jan 23 '16 at 10:55

2 Answers2

0

DirectoryIterator let you obtain filenames relatives to the directory not absolute, neither relative to the current directory of your process. Concatenate $directory and $fileinfo->getFileName() to obtain a correct usable path.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

Here is a solution:

$path = 'PATH';

if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        //skips dots  
        if ('.' === $file) continue;
        if ('..' === $file) continue;
        //ignore folders
        if ('FOLDER_TO_IGNORE' === $file) continue;

        //check if filename is a folder
        if (is_dir($file)){
        //DO SOMETHING WITH FOLDER ($file)
        }

    }
    closedir($handle);
}
Nik
  • 139
  • 2
  • 14