How can PHP scripts be optimized to exclude certain files, like index.php, from directory listings?

To optimize PHP scripts to exclude certain files, like index.php, from directory listings, you can use the following code snippet. By checking the filename against a list of excluded files, you can prevent them from being displayed in the directory listing.

<?php
$excludedFiles = ['index.php', 'file2.php', 'file3.php']; // List of files to exclude

$files = scandir('./'); // Get list of files in current directory

foreach ($files as $file) {
    if (!in_array($file, $excludedFiles) && is_file($file)) {
        echo $file . "<br>";
    }
}
?>