What best practices should be followed when handling file downloads in PHP?

When handling file downloads in PHP, it is important to set the appropriate headers to ensure the file is downloaded correctly by the browser. This includes setting the content type, content length, and content disposition headers. Additionally, it is recommended to use readfile() function to efficiently output the file content to the browser.

$file = 'path/to/file.pdf';

if (file_exists($file)) {
    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;
} else {
    echo 'File not found.';
}