What are the security implications of using user input directly in file download scripts in PHP?

Using user input directly in file download scripts in PHP can lead to security vulnerabilities such as directory traversal attacks or arbitrary file downloads. To mitigate these risks, it is important to validate and sanitize user input before using it to determine the file to download. This can be done by restricting the file path to a specific directory or using a whitelist approach to only allow certain file extensions to be downloaded.

// Validate and sanitize user input before using it in file download script
$allowed_files = array("file1.pdf", "file2.jpg", "file3.txt");
$requested_file = $_GET['file'];

if (in_array($requested_file, $allowed_files)) {
    $file_path = "/path/to/files/" . $requested_file;
    
    // Code to download the file securely
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
    readfile($file_path);
    exit;
} else {
    echo "Invalid file requested";
}