What are some best practices for handling directory listings in PHP scripts?

When handling directory listings in PHP scripts, it is important to ensure that sensitive information is not exposed to potential attackers. One way to address this is to disable directory listings altogether by configuring the web server appropriately. Additionally, you can use PHP code to check if a directory listing is enabled and then handle the output accordingly to prevent unauthorized access to directory contents.

<?php
// Check if directory listing is enabled
if (is_dir($directory)) {
    if (!is_readable($directory)) {
        // Directory listing is disabled
        echo "Directory listing is disabled.";
    } else {
        // Handle directory listing
        $files = scandir($directory);
        foreach ($files as $file) {
            echo $file . "<br>";
        }
    }
} else {
    echo "Directory does not exist.";
}
?>