Nathan Campos
Nathan Campos

Reputation: 29497

Listing Files Using PHP

I'm needing to make a web site, that should list all the files that are in the directory /Files(where / is the Apache public - htdocs), but excluding if there is any sub-directory. Also, they should have links for every file. Like this:

echo "<a href='Link to the file'>Test.doc</a>" . "\n"

How could I do it?

Upvotes: 0

Views: 159

Answers (2)

Gordon
Gordon

Reputation: 316969

glob finds files by a matching pattern. That's not needed here, so you could also use the DirectoryIterator:

foreach(new DirectoryIterator('/pub/files') as $directoryItem) {
    if($directoryItem->isFile()) {
        printf('<a href="/files/%1$s">%1$s</a>', $directoryItem->getBasename());
    }
}

Further reading:

Upvotes: 4

Christian
Christian

Reputation: 28124

Use "glob()" function.

<?php
    foreach(glob('/*') as $file)
      if(is_file($file))
        echo '<a href="'.$file.'">'.basename($file).'</a>';
?>

For your info, this kind of thing is called "directory listing", which Apache sometimes does by default when there's no index (html, htm, php asp..) file.

Upvotes: 2

Related Questions