What are some best practices for handling directory listings in PHP to ensure efficiency and security?

When handling directory listings in PHP, it is important to ensure both efficiency and security. To achieve this, you can disable directory listings by setting `Options -Indexes` in your .htaccess file or by using PHP to handle directory listings with a script that filters and sanitizes the output to prevent unauthorized access to sensitive files.

<?php
// Prevent directory listing in PHP
$directory = 'path/to/directory';

if (is_dir($directory)) {
    $files = array_diff(scandir($directory), array('..', '.'));
    
    foreach ($files as $file) {
        // Filter and sanitize file names before displaying
        $safeFileName = htmlspecialchars($file);
        echo "<a href='$directory/$file'>$safeFileName</a><br>";
    }
} else {
    echo "Directory not found.";
}
?>