What best practices should PHP developers follow when handling MIME types for different file formats?

When handling MIME types for different file formats in PHP, developers should validate and sanitize user input to prevent malicious attacks like file upload vulnerabilities. It is essential to use PHP functions like finfo_file() or mime_content_type() to determine the MIME type of uploaded files accurately. Additionally, developers should always set the appropriate Content-Type header when serving files to ensure compatibility with browsers and prevent security risks.

// Validate and sanitize user input
$uploadedFile = $_FILES['file']['tmp_name'];

// Determine MIME type using finfo_file()
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $uploadedFile);
finfo_close($finfo);

// Set appropriate Content-Type header
header('Content-Type: ' . $mimeType);