Skip to main content
Nancy OShea
Community Expert
September 30, 2012
Answered

PHP contents of folder

  • September 30, 2012
  • 1 reply
  • 1128 views

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.

This topic has been closed for replies.
Correct answer David_Powers

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>';

    }

}

?>

1 reply

David_Powers
Inspiring
October 1, 2012

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/>";

?>

David_Powers
David_PowersCorrect answer
Inspiring
October 1, 2012

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>';

    }

}

?>

Nancy OShea
Community Expert
October 1, 2012

I think your alternative is a much better approach.

Thank you so much!!

Nancy O.

Nancy O'Shea— Product User, Community Expert & Moderator