PHP scandir causing extra files
Why is it when i use scandir using PHP i get开发者_运维技巧 extra values
$portID = $this->id;
$dir = '/home/sites/mydomain.com/public_html/public/images/'.$portID;
$contents = scandir($dir);
Is there something i dont know about the function which produces more values than are actually in the folder?
here's an alternative using opendir
$dir = "/your/path";
if (is_dir($dir)) {
if ($d = opendir($dir)) {
while (($file = readdir($d)) !== false) {
if ( $file != "." && $file != ".." ){
echo "filename: $file \n";
$files[]=$file;
}
}
closedir($d);
}
}
if you insist on using scandir(), then use a loop to go through the array of files returned by scandir(), and then remove those you don't want from the array
I don't have enough rep to comment on just somebody's answer so this will have to be in a separate answer. As of PHP 5.3 there is the FilesystemIterator which extends the DirectoryIterator and skips dot-files by default.
Here is the easiest way to get rid of the dots and unnecessary files or directories.
// remove unnecessary dots etc
$result = array_diff(scandir('/dir/to/scan/'), array('.', '..', '.DS_Store'));
print_r($result);
Hope this is helpful. Thanks!
there's nothing wrong with Pekka's answer; I'll just add a more declarative and mockable realization from SPL:
class DirectoryFilterDots extends RecursiveFilterIterator
{
function __construct($path)
{
parent::__construct(new RecursiveDirectoryIterator($path));
}
function accept()
{
return !$this->getInnerIterator()->isDot();
}
function key()
{
return $this->getInnerIterator()->getPathname();
}
}
While it's hard to tell without the actual output of scandir(), I guess you mean the additional .
and ..
entries.
They show up in the examples in the manual as well. You will have to filter them out manually.
.
refers to the current directory
..
refers to the parent directory.
This tradition comes from the Unix world, where exactly historically, I don't know. I guess it is because it allows you to quickly see the permissions for the current and parent directories on each call of ls
.
精彩评论