How can PHP headers be optimized for file downloads to ensure compatibility with various browsers?

To optimize PHP headers for file downloads and ensure compatibility with various browsers, it is important to set the appropriate content type and disposition headers. This includes setting the Content-Type header to the correct MIME type for the file being downloaded and setting the Content-Disposition header to specify how the browser should handle the file (e.g., as an attachment rather than displaying it in the browser window).

<?php
$file_path = 'path/to/your/file.pdf';

if (file_exists($file_path)) {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
    readfile($file_path);
    exit;
} else {
    echo 'File not found';
}
?>