Force File Download with PHP Using Header()
Issue:
Despite various attempts, users experience difficulties in prompting file downloads from a server using PHP's header() function. They observe the necessary headers being sent but encounter issues with displaying the save dialog.
Solution:
To successfully force file downloads, the headers must be set appropriately. The following code addresses the concerns raised:
$quoted = sprintf('"%s"', addcslashes(basename($file), '"\')); $size = filesize($file); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $quoted); header('Content-Transfer-Encoding: binary'); header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $size);
Key Differences from Previous Attempts:
Verified Browsers:
This solution has been confirmed to work in Firefox 8.0.1, Chrome 15.0.874.121, and Safari 5.1.1.
The above is the detailed content of How Can I Force File Downloads in PHP Using `header()` and Avoid Browser Display Issues?. For more information, please follow other related articles on the PHP Chinese website!