Scott B
Scott B

Reputation: 40157

DirectoryIterator scan to exclude '.' and '..' directories still including them?

In the script below, I'm trying to copy the folders that exist in the $base directory over to the $target directory. However, in my initial echo test, its returning the . and .. directories even though I'm trying to handle that exception in the conditional.

What am I missing?

    $base = dirname(__FILE__).'/themes/';
    $target = dirname( STYLESHEETPATH );
    $directory_folders = new DirectoryIterator($base); 
    foreach ($directory_folders as $folder) 
    {
         if ($folder->getPath() !== '.' && $folder->getPath() !=='..' ) 
         {
            echo '<br>getPathname: '. $folder->getPathname();
            //copy($folder->getPathname(), $target);
         }
    }die;

However, and this makes no sense to me, if I change the conditional to...

         if (!is_dir($folder) && $folder->getPath() !== '.' && $folder->getPath() !=='..' ) 

It returns the correct folders inside of $base. What?

Upvotes: 3

Views: 2393

Answers (2)

meze
meze

Reputation: 15087

You can use DirectoryIterator::isDot instead:

if (!$folder->isDot()) 

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

DirectoryIterator::getPath() returns the full path to the directory -- and not only the last part of it.

If you only want the last portion of that path, you should probably use SplFileInfo::getBasename() in your condition.

Or, for your specific test, you might want to take a look at the DirectoryIterator::isDot() method (quoting) :

Determine if current DirectoryIterator item is '.' or '..'

Upvotes: 3

Related Questions