What are some best practices for downloading files with PHP?

When downloading files with PHP, it is important to set the correct headers to ensure the file is downloaded properly. One common issue is files being displayed in the browser instead of being downloaded. To solve this, you need to set the Content-Disposition header to attachment.

<?php
$file = 'path/to/file.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;
?>