Home > Backend Development > PHP Tutorial > How to Force File Downloads with PHP Using `header()`?

How to Force File Downloads with PHP Using `header()`?

DDD
Release: 2024-12-04 14:54:10
Original
257 people have browsed it

How to Force File Downloads with PHP Using `header()`?

Force File Download with PHP Using header()

1. The Problem:

You're attempting to enable users to download files from your server but the file is not prompting a "Save As" dialog.

2. The Cause:

Incorrect content type declaration in the header.

3. The Solution:

Ensure that the content type header is set to application/octet-stream for file downloads:

header('Content-Type: application/octet-stream');
Copy after login

4. Additional Tips:

  • Use the addcslashes function to protect the filename from characters that may break the header.
  • Set a specific filename for the downloaded file using Content-Disposition: attachment; filename= header.
  • Specify the content length using the Content-Length header.
  • Add headers to prevent caching and ensure the file is saved rather than displayed in the browser.

5. Example Code:

$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);
readfile($file);
Copy after login

The above is the detailed content of How to Force File Downloads with PHP Using `header()`?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template