What best practices should be followed when using header functions in PHP to ensure proper file downloads without errors?

When using header functions in PHP for file downloads, it is important to set the appropriate headers to ensure proper handling of the file. 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 indicate the size of the file. Additionally, it is recommended to use ob_clean() and flush() functions before sending the file to avoid any output buffering issues.

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

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

ob_clean();
flush();
readfile($file);
exit;
?>