What are best practices for handling file downloads in PHP scripts to ensure compatibility with different file types and prevent header errors?

When handling file downloads in PHP scripts, it is important to set the correct headers to ensure compatibility with different file types and prevent header errors. This can be achieved by using the header() function to specify the content type and disposition of the file being downloaded. Additionally, it is recommended to use readfile() function to output the file contents.

<?php
$file = 'example.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
?>