Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scandir returns [0] =>. and [1]=>.. in array

Tags:

php

I have a simple PHP script with this snippet of code:

$files  = scandir($dir);    
print_r($files);

And noticed in my array i have:

    [0] => .
    [1] => ..
    [2] => assets.php
    [3] => loader.php

Is this a bug on my server or is it expected behavior, what are they? And if it's the latter is there any way to exclude them from the scan? As I wish to only get script files that I made from the directory and nothing else. Is there any way to exclude them from the scan?

like image 303
Sir Avatar asked Nov 22 '25 08:11

Sir


1 Answers

No it isn't a bug.... . is the current directory, .. the parent directory

See the PHP Docs

The user-contributed notes show one way of excluding them:

$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));

If you use other options besides scandir, such as SPL's DirectoryIterator, there's options to exclude them (such as combining it with a RegexIterator), or to test for them as you're iterating:

$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
like image 152
Mark Baker Avatar answered Nov 24 '25 00:11

Mark Baker