In what scenarios would it be advisable to use directory listings in a PHP application, and are there any best practices to follow when doing so?

Directory listings in a PHP application can be useful for displaying the contents of a directory to users, such as a list of files or folders. This can be helpful for navigation or providing access to resources. However, it is important to ensure that directory listings are only enabled for directories where it is safe to do so, as it can potentially expose sensitive information. It is recommended to restrict directory listings to only public directories and to disable them for any directories containing sensitive data.

// Example of enabling directory listings for a specific directory
$directory = 'public_files/';

if (is_dir($directory)) {
    $files = scandir($directory);
    
    foreach ($files as $file) {
        echo $file . "<br>";
    }
} else {
    echo "Directory does not exist.";
}