What are best practices for setting content types and headers when using readfile in PHP for file downloads?

When using readfile in PHP for file downloads, it is important to set the appropriate content type and headers to ensure the file is downloaded correctly. This includes setting the content type to the appropriate MIME type for the file being downloaded and sending headers to specify the file name and content disposition. Failure to set these correctly can result in the file not being downloaded or opened correctly by the user's browser.

$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;