What are the best practices for handling file downloads in PHP to ensure a seamless user experience?

When handling file downloads in PHP, it is important to set the appropriate headers to ensure a seamless user experience. This includes setting the Content-Type header to specify the type of file being downloaded, the Content-Disposition header to prompt the browser to download the file instead of displaying it, and the Content-Length header to specify the size of the file. Additionally, it is recommended to use readfile() function to efficiently output the file contents.

<?php
$file = 'example.pdf';

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));

readfile($file);
exit;
?>