What are some best practices for handling file downloads in PHP scripts?
When handling file downloads in PHP scripts, it is important to set the appropriate headers to ensure the file is downloaded correctly by the browser. This includes setting the Content-Type header to the appropriate MIME type of the file, Content-Disposition header to indicate the file should be downloaded as an attachment, and Content-Length header to specify the size of the file.
<?php
$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-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found.';
}
?>