Home >Backend Development >PHP Tutorial >How to reliably force file downloads using PHP headers?

How to reliably force file downloads using PHP headers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 12:38:10719browse

How to reliably force file downloads using PHP headers?

Force File Download Using Header() in PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn