What are the best practices for setting headers when offering a file download in PHP?

When offering a file download in PHP, it is important to set the appropriate headers to ensure the file is downloaded correctly by the browser. This includes setting the Content-Type header to specify the file type, Content-Disposition header to prompt the browser to download the file instead of displaying it, and Content-Length header to specify the file size. Additionally, it is recommended to use an appropriate file name in the Content-Disposition header to give the user a meaningful name for the downloaded file.

<?php
// Set headers for file download
$file = 'example.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));

// Output the file for download
readfile($file);
exit;
?>