What potential pitfalls should be avoided when using PHP to display specific file types as download links?

One potential pitfall to avoid when using PHP to display specific file types as download links is not properly sanitizing user input, which can lead to security vulnerabilities such as directory traversal attacks. To mitigate this risk, always validate and sanitize the file path before outputting it as a download link.

<?php
// Sanitize user input to prevent directory traversal attacks
$filename = basename($_GET['file']);

// Validate file type to only allow specific file types
$allowed_types = array('pdf', 'docx', 'txt');
$file_extension = pathinfo($filename, PATHINFO_EXTENSION);

if (in_array($file_extension, $allowed_types)) {
    // Output the file as a download link
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    readfile('path/to/files/' . $filename);
} else {
    echo 'Invalid file type';
}
?>