tags:

views:

88

answers:

2

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?

+2  A: 

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.

Christian Sciberras
Sorry, will fix my code..done.
Christian Sciberras
don't use `*.*` as the pattern. `*` works fine and matches files without an extension (or files that just have an extension)
Yacoby
Doesn't that also match folders? Let me change the code again...fixed
Christian Sciberras
Looks like a PHP issue to me. Do you have PHP installed and enabled?If you go to View->View Source, you'll see the full PHP code, which is not right. That is, the file is not executed at all.
Christian Sciberras
+4  A: 

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:

Gordon
For what it's worth, the DirectoryIterator doesn't return SplFileInfo. Not that that makes any difference to the code shown.
salathe
@salathe ok, current() returns DirectoryIterator, which extends from SplFileInfo? Better? :)
Gordon
@Gordon yep, better!
salathe
@Gordon: It works, but when I click on the links, what I got is this: `The requested URL ... was not found on this server.`. Check it out: surl.x10.mx/list.php
Nathan Campos
@Nathan if you look at the href attribute, you will see they have the full server path, e.g. `/home/nathanpc/public_html/filename` - this won't work. A `/` at the beginning of a URI means relative to the document root, so the link points to the server path `/home/nathanpc/public_html/home/nathanpc/public_html/filename`. If the filename is in public_html, just use `/filename`.
Gordon
Thanks very much!
Nathan Campos