What potential pitfalls should be considered when manipulating content types in PHP for file downloads?

When manipulating content types in PHP for file downloads, one potential pitfall to consider is ensuring that the content type matches the actual file being downloaded. This is important for security reasons as misrepresenting the content type can lead to vulnerabilities such as content sniffing attacks. It is also important to properly handle file extensions and sanitize user input to prevent any malicious files from being downloaded.

// Set the correct content type based on the file extension
$file = 'example.pdf';

$mime_types = array(
    'pdf' => 'application/pdf',
    'doc' => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    // Add more file types as needed
);

$extension = pathinfo($file, PATHINFO_EXTENSION);
$content_type = isset($mime_types[$extension]) ? $mime_types[$extension] : 'application/octet-stream';

header("Content-Type: $content_type");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);