Workaround for directory-browsing
Took this from your blog post:


  What I need to do is this:
  
  
  take a directory on the URL, which by default will be the current directory;
  list the files / directories;
  for each entry, convert the filesystem path to a URL, using the current HTTP host and port;
  also provide a "parent directory" link too, for browsing upstream.
  


Knowing these requirements, your code is way too complicated. That's quite normal for a beginner with PHP, so it's no problem. PHP offers built-in solutions that from time to time make experienced PHP programmers think: "Why didn't I find that before?" -- So what you missed, is glob(), and maybe some other neat functions.

// Directory to create listing for, defaulting to the current one
$dirCurrent = '';
if (!empty($_GET['dir'])) {
    // Remove leading and trailing slashes
    $dirCurrent = trim($_GET['dir'], '/.');
}
if (!empty($dirCurrent)) {
    $dirCurrent .= '/';
}
$dirBase = realpath($_SERVER["DOCUMENT_ROOT"]);

// Since we make $dirCurrent relative, a basedir check is not needed
if (is_dir($dirBase . '/' . $dirCurrent)) {
    // Provide a link to go up a level
    if (!empty($dirCurrent)) {
        $parentDir = dirname($dirCurrent);
        $parentLinkUrl = $_SERVER["SCRIPT_NAME"] . "?dir=" . $parentDir;
        echo "&lt;a href=\"$parentLinkUrl\"&gt;[Parent Directory]&lt;/a&gt;&lt;br&gt;";
    }
    echo "&lt;ul&gt;";
    foreach (glob("$dirBase/$dirCurrent*") as $entry) {
        // Hidden files (those starting with a dot) are not returned by glob
        $linkText = basename($entry);
        if (is_dir($entry)) {
            // We just want to link back to this file, passing the dir
            $linkUrl = $_SERVER["SCRIPT_NAME"] . "?dir=" . urlencode($dirCurrent . basename($entry));
            $linkText .= "/"; // Just to make it more clear it's a dir
        } else {
            // we want a link to the actual file
            $linkUrl = $dirCurrent . basename($entry);
        }
        echo "&lt;li&gt;&lt;a href=\"$linkUrl\"&gt;$linkText&lt;/a&gt;&lt;/li&gt;";
    }
    echo "&lt;/ul&gt;";
} else {
    header("HTTP/1.0 404 Not Found");
}