Force File Download Using PHP's header() Function
When attempting to offer file downloads to users from your server, you may encounter unexpected challenges. In PHP, the header() function is commonly used for this purpose, but various code examples often yield disappointing results.
For instance, consider the following code:
$size = filesize("Image.png"); header('Content-Description: File Transfer'); header('Content-Type: image/png'); header('Content-Disposition: attachment; filename="Image.png"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $size); readfile("Image.png");
Despite setting the necessary headers, including the correct Content-Disposition to trigger the file download dialog, the desired behavior fails to occur.
Solution:
To remedy this issue, ensure that the Content-Type header is set to "application/octet-stream" instead of "image/png" or any other mime type. For instance, the following headers should consistently force file downloads:
$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);
By using these headers, you should be able to reliably force file downloads from your PHP web applications.
The above is the detailed content of How Can I Reliably Force File Downloads Using PHP's `header()` Function?. For more information, please follow other related articles on the PHP Chinese website!