Temüjin
Temüjin

Reputation: 15548

Is it safe to use array_slice to remove scandir dot and dot-dot entries?

I want to use array_slice with scandir in my PHP script.

Normal usage:

<?php

$files = scandir('/path/to/files');

foreach($files as $file) {
    if($file != '.' && $file != '..') {
        // Do something here...
    }
}

My example:

<?php

$files = array_slice(scandir('/path/to/files'), 2);

foreach($files as $file) {
    // Do something here...
}

My doubt is, is it safe or not to use this type of logic ?

Upvotes: 3

Views: 787

Answers (2)

Boann
Boann

Reputation: 50041

It is definitely not safe. The following example creates a directory with a file called !. When scandir sorts the results, ! appears before . and ..:

mkdir('test');
touch('test/!');
print_r(scandir('test'));
unlink('test/!');
rmdir('test');

Output:

Array
(
    [0] => !
    [1] => .
    [2] => ..
)

In general, this will be an issue for all filenames starting with a character which sorts before .. That includes some unprintable characters which probably won't exist in real world data, but it also applies to common punctuation including ! # $ % & ( ) + -.

Even if it worked, I wouldn't recommend it, as using array_slice there makes the intent of the code less clear.

Upvotes: 3

edigu
edigu

Reputation: 10099

Instead of trying to scan directory by old-school ways, i strongly recommend using of SPL Directory Iterator for such requirement.

Try this:

$iterator = new \DirectoryIterator('/path/to/files');
foreach ($iterator as $file) {
    if($file->isDot()) {
        continue;
    }
    /** Now here you can use lot of SplFileInfo interface methods here */
    // $file->getFilename();
    // $file->isFile();
    // $file->isDir();
    // $file->getSize();
}

Upvotes: 1

Related Questions