What are the best practices for handling file downloads in PHP to avoid unwanted HTML code in the downloaded files?

When handling file downloads in PHP, it's important to set the correct headers to ensure that the file is downloaded as-is without any unwanted HTML code. This can be achieved by setting the Content-Type header to application/octet-stream and using readfile() function to output the file contents directly to the browser.

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

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));

readfile($file);
exit;
?>