What are some best practices for handling file downloads in PHP to prevent corruption?

When handling file downloads in PHP, it's important to set the correct headers to prevent corruption. This includes setting the Content-Type header to the appropriate MIME type, Content-Disposition to indicate it's an attachment, and Content-Length to specify the file size. Additionally, using readfile() function to read and output the file content can help prevent corruption.

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