How can user input validation be implemented to prevent malicious file downloads in PHP scripts?

User input validation can be implemented in PHP scripts by checking the file extension and content type before allowing a file to be downloaded. This can prevent malicious files from being downloaded onto the server or client machine.

// Check if the file extension and content type are valid before allowing download
$allowedExtensions = ['pdf', 'doc', 'docx', 'txt'];
$allowedContentTypes = ['application/pdf', 'application/msword', 'text/plain'];

$uploadedFile = $_FILES['file'];

if (in_array(pathinfo($uploadedFile['name'], PATHINFO_EXTENSION), $allowedExtensions) && in_array($uploadedFile['type'], $allowedContentTypes)) {
    // Allow file download
    header('Content-Type: ' . $uploadedFile['type']);
    header('Content-Disposition: attachment; filename=' . $uploadedFile['name']);
    readfile($uploadedFile['tmp_name']);
} else {
    // Invalid file type, do not allow download
    echo 'Invalid file type. Please upload a valid file.';
}