Copy link to clipboard
Copied
Hi,
I'm trying to print a list of files that are located in sub, sub folders.
and my directory.php page is at site root level.
Sitename:
+fee
+fi
+foo
file1
file2
file3, etc...
directory.php
The code I'm using works great at producing a list of links. But when you click on links to files, the paths are all wrong and I'm getting 404 errors.
<?php
$dir = "fee/fi/foo";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh)))
{
if($filename!='.'&&$filename!='..')
$files[] = $filename;
}
sort($files);
foreach($files as $value) echo "<a href='{$value}'>{$value}</a><br/>";
?>
What am I missing?
Thanks,
Nancy O.
An alternative way of doing this would be to use a DirectoryIterator like this:
<?php
$dir = "fee/fi/foo";
$files = new DirectoryIterator($dir);
foreach ($files as $file) {
if (!$file->isDot() && !$file->isDir()) {
echo '<a href="' . $file->getPathName() . '">' . $file . '</a><br>';
}
}
?>
Copy link to clipboard
Copied
You're missing the path to the subfolder. All that you're getting is the filename, not the full path:
<?php
$dir = "fee/fi/foo";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh)))
{
if($filename!='.'&&$filename!='..')
$files[] = $filename;
}
sort($files);
foreach($files as $value) echo "<a href='fee/fi/foo/{$value}'>{$value}</a><br/>";
?>
Copy link to clipboard
Copied
An alternative way of doing this would be to use a DirectoryIterator like this:
<?php
$dir = "fee/fi/foo";
$files = new DirectoryIterator($dir);
foreach ($files as $file) {
if (!$file->isDot() && !$file->isDir()) {
echo '<a href="' . $file->getPathName() . '">' . $file . '</a><br>';
}
}
?>
Copy link to clipboard
Copied
I think your alternative is a much better approach.
Thank you so much!!
Nancy O.
Copy link to clipboard
Copied
David,
Using your alternative approach, now I've got a backslash appearing in the link path.
domain.com/fee/fi/foo\file1.doc
Where is that coming from?
Nancy O.
Copy link to clipboard
Copied
The backslash comes from Windows. Fortunately, browsers are savvy enough to deal with it.
The alternative would be to use the literal path instead of $file->getPathName().
echo '<a href="fee/fi/fo/' . $file . '">' . $file . '</a><br>';
Copy link to clipboard
Copied
I used a literal path because FF on my local testing server couldn't resolve the backslash. 😞
Anyway, here's the hybrid code I'm using and it works great!
<ul>
<?php
$dir = "FEE/FI/FOO";
$files = new DirectoryIterator($dir);
foreach ($files as $file) {
if (!$file->isDot() && !$file->isDir()) {
echo '<li><a href="FEE/FI/FOO/' . $file . '">' . $file . '</a> - ' .$file->getSize() .' bytes </li>';
}
}
?>
</ul>
Thanks, David.
Nancy O.