Reputation: 93
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
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:
Difference between DirectoryIterator and FileSystemIterator
Upvotes: 2
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