What are some best practices for handling directory listings and outputting links in PHP?

When outputting directory listings in PHP, it is important to ensure that sensitive information is not exposed to users. To handle directory listings safely, it is recommended to disable directory browsing and only output links to files within the directory. This can be achieved by using the scandir() function to retrieve a list of files in the directory and then filtering out any unwanted files or directories before outputting links.

$directory = "path/to/directory";

$files = array_diff(scandir($directory), array('..', '.'));

foreach($files as $file){
    if(is_file($directory . '/' . $file)){
        echo "<a href='" . $directory . "/" . $file . "'>" . $file . "</a><br>";
    }
}