Can array_slice be used to remove scandir dot and dot-dot?
I want to use array_slice
with scandir
in my PHP script.
Common 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...
}
I doubt it is safe or not to use this type of logic?
source to share
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 a problem for all filenames, starting with the character that is sorted to .
. This includes some non-printable characters that probably won't exist in real-world data, but also apply to general punctuation including ! # $ % & ( ) + -
.
Even if it worked, I would not recommend it, as using array_slice makes the code less readable.
source to share
Instead of trying to scan a directory for old age, I highly recommend using the SPL Directory Destroyer for such a requirement.
Try the following:
$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();
}
source to share