When attempting to enable users to download files from a server, common solutions like the one below may not work:
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");
The save dialog may not appear, despite the console displaying the correct headers.
The crucial error lies in the Content-Type header. For file downloads, it should not be image/png, but rather:
header('Content-Type: application/octet-stream');
A reliable set of headers for file downloads is as follows:
$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 ensuring that the correct headers are sent, users will be prompted with a save dialog when attempting to download files from the server.
The above is the detailed content of How to reliably force file downloads using PHP headers?. For more information, please follow other related articles on the PHP Chinese website!