Home > Backend Development > PHP Tutorial > How Can I Reliably Force File Downloads Using PHP's `header()` Function?

How Can I Reliably Force File Downloads Using PHP's `header()` Function?

Mary-Kate Olsen
Release: 2024-12-29 02:08:11
Original
602 people have browsed it

How Can I Reliably Force File Downloads Using PHP's `header()` Function?

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");
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template