What are some common mistakes to avoid when trying to replicate the autoindex feature in PHP for directory listing?

One common mistake to avoid when trying to replicate the autoindex feature in PHP for directory listing is not properly handling file permissions. It is important to ensure that the PHP script has the necessary permissions to read the directory and files within it. Additionally, failing to sanitize user input can lead to security vulnerabilities such as directory traversal attacks.

<?php
$directory = '/path/to/directory/';

if (is_dir($directory)) {
    if ($handle = opendir($directory)) {
        echo "<ul>";
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                echo "<li><a href='" . $directory . $entry . "'>" . $entry . "</a></li>";
            }
        }
        echo "</ul>";
        closedir($handle);
    }
} else {
    echo "Invalid directory.";
}
?>