Reputation: 4340
I have written this simple script display all the files in a directory as a set of buttons.
This code reads from the upload directory and displays all files inside a submit button in a form.
$handle = opendir("upload");
echo '<form name="form" method="post" action="download.php">';
while($name = readdir($handle)) {
echo '<input type="submit" name="file" value='.$name.' />';
}
echo '</form>';
Now the issue here is; every time I run the script I find two button at the beginning with contents .
and ..
I have not been able to figure out what causes this issue.
Upvotes: 0
Views: 51
Reputation: 63797
What you have encountered are two special files used by the file system.
.
represents the current directory you are in.1
..
represents the parent directory of the current directory.2
Footnotes:
1. A path such as "/my_dir/././././././file" is equivalent to "/my_dir/file".
2. A path such as "/my_dir/../my_dir/../my_dir/file" is equivalent to "/my_dir/file" since ..
will make you move "up" one level.
To get around the issue of showing these two to your user filter the content returned by readdir
using something as the below:
while ($name = readdir ($handle)) {
if ($name == '.' || $name == '..')
continue; /* don't echo anything, skip to next read */
echo '<input type="submit" name="file" value='.$name.' />';
}
Upvotes: 3
Reputation: 12244
Another solution is to use a FilesystemIterator like this:
foreach(new FilesystemIterator('upload') as $file){
echo $file;
}
It will automatically skip . and .. entries in the filesystem.
Upvotes: 0
Reputation: 313
the directory listing includes . for the current dir and .. for the parent dir.
I usually use this that i got from the PHP manual (http://php.net/manual/en/function.readdir.php)
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
so what you need to do is to exclude the . and .. from the output.
Upvotes: 0