What are best practices for setting headers in PHP to ensure successful file downloads without errors?
When setting headers in PHP for file downloads, it is important to ensure that the headers are set correctly to prevent errors during the download process. One common issue is the headers being sent too late or not being set properly, which can result in corrupted files or failed downloads. To avoid this, it is recommended to set the necessary headers before any output is sent to the browser.
<?php
$file_path = 'path/to/your/file.pdf';
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
echo 'File not found';
}
?>