What are some potential pitfalls when using PHP to automatically link files from a specific folder?

One potential pitfall when automatically linking files from a specific folder in PHP is that the code may be vulnerable to directory traversal attacks if not properly sanitized. To mitigate this risk, it is important to validate and sanitize the file names before including them in the links.

$folder = 'path/to/folder/';

$files = scandir($folder);

foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        $safeFileName = htmlspecialchars($file);
        echo "<a href='$folder$safeFileName'>$safeFileName</a><br>";
    }
}