user3526766
user3526766

Reputation: 93

read file name from directory

I want to read html file name from directory without any database. I have a code and its working properly, but two blank name it is giving, while I have only 4 file in directory.

<?php
 if (is_dir('dir')) {
if ($dh = opendir('dir')) {
    while (($file = readdir($dh)) !== false) {
        echo "filename:".$file."<br />";
    }
}
}?>

I have 4 html file and output should be:

filename:aaaaaa kjnnk_13.html
filename:aaaaaa kjnnk_2.html
filename:aaaaaa kjnnk_6.html
filename:aaaaaa kjnnk_9.html

But I found 2 extra filename:

filename:.
filename:..
filename:aaaaaa kjnnk_13.html
filename:aaaaaa kjnnk_2.html
filename:aaaaaa kjnnk_6.html
filename:aaaaaa kjnnk_9.html

Please help

Upvotes: 1

Views: 11856

Answers (2)

Michel
Michel

Reputation: 960

Alternatively you could use FilesystemIterator which would skip the dot files by default:

$it = new FilesystemIterator('dir');
foreach ($it as $fileinfo) {
    echo $fileinfo->getFilename() . "<br/>";
}

more answers in stackoverflow:

What exactly are the benefits of using a PHP 5 DirectoryIterator over PHP 4 "opendir/readdir/closedir"?

PHP: scandir() is too slow

Difference between DirectoryIterator and FileSystemIterator

Upvotes: 2

Ivo P
Ivo P

Reputation: 1712

. is for current dir .. is for one directory up

When using readdir you will get those 2 extra.

I prefer using glob(). That function lets you filter for html files only too

<?php
   $files = glob('dir/*html');
   foreach($files as $file) {
       echo "filename:".$file."<br />";
   }
?>

Upvotes: 5

Related Questions