What are the potential pitfalls of automatically generating links in a dropdown menu from files in a directory?

Automatically generating links in a dropdown menu from files in a directory can lead to security vulnerabilities such as directory traversal attacks or exposing sensitive information. To solve this issue, it is important to sanitize the file names and ensure that only allowed file types are included in the dropdown menu.

$directory = "path/to/directory";
$allowed_file_types = array("pdf", "doc", "docx");

$files = scandir($directory);
foreach ($files as $file) {
    $file_extension = pathinfo($file, PATHINFO_EXTENSION);
    if (in_array($file_extension, $allowed_file_types)) {
        $safe_file_name = htmlspecialchars($file);
        echo "<option value='$directory/$file'>$safe_file_name</option>";
    }
}