File listing showing nerdy folders


$path = '/';

$handle = @opendir($path) or die("Unable to open $path");

echo '<ol>';

while ($file = readdir($handle))
{
	printf('<li><a href="?file=%s">%s</a></li>', $file, $file);	
}

echo '</ol>';

closedir($handle);

This code is in a PHP file in a folder which contains a lot of Flash movies. When I view the page, it lists all these nerdy folders (which i’ve never seen before) and doesn’t list any of the Flash movies.


   1. .
   2. ..
   3. pgp_key.asc
   4. tmp
   5. proc
   6. homepages
   7. srv
   8. bin
   9. boot
  10. media
  11. dev
  12. etc
  13. initrd
  14. lib
  15. mnt
  16. opt
  17. root
  18. sbin
  19. usr
  20. var
  21. kunden
  22. .depdblock5
  23. .lock5
  24. .depdb5
  25. .filemap5
  26. lost+found
  27. .registry
  28. .filemap
  29. .lock
  30. .depdblock
  31. .depdb

I tried changing path to the absolute path: http://www.site.com/folder, but the die() was called saying that it couldn’t open that folder.

What you are calling an “absolute path” is not the path you are thinking of. http://www.site.com/folder is the url (Universal Resource Locator) of ‘folder’ on the web. What you want is the path to your resource on the web server. Try something like this:


$path = getenv("DOCUMENT_ROOT") . "/folder";

$handle = @opendir($path) or die("Unable to open $path");
echo '<ol>';
while(false !== ($file = readdir($handle))) {
  if(($file == ".") || ($file == "..")) {
    continue;
  }
  printf('<li><a href="?file=%s">%s</a></li>', $file, $file);    
}
echo '</ol>';
closedir($handle);

Note the changes I made to your while loop and the if statement just after that.

Hope that helps…

Your code works. Thanks.

I recall that I did not have to prefix my path with getenv(“DOCUMENT_ROOT”) on a different host and this same code worked. Why is that? (I use www.1and1.com now).

Honestly, I’m not really sure. The safest, and most portable way of accessing files on the web server (not via http) is by using the DOCUMENT_ROOT environment variable. The reason is that DOCUMENT_ROOT will always point to your public_html (or htdocs) directory… no matter how the hosting company has configured their server. Now, this is different from, say, giving relative paths to things like images in html pages. Say your home directory on your shared server is “/home/neodreamer/public_html/.” You can set an image’s src attribute to something like “/images/image.jpg” and it automatically serves the image located at /home/neodreamer/public_html/images/image.jpg"

Hope that makes sense…