Home >Backend Development >PHP Tutorial >How Can I Force File Downloads in PHP?

How Can I Force File Downloads in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 05:44:10229browse

How Can I Force File Downloads in PHP?

Forcing File Downloads in PHP

When clicking a link to download a CSV file, users often face the issue of the file opening in the browser instead of downloading. This problem stems from the default behavior of servers, which is to display text files within the browser. To force the download, PHP provides several solutions.

.htaccess Solution

For a global solution, add the following line to your .htaccess file:

AddType application/octet-stream csv

This instructs the server to treat all CSV files as binary data that should be downloaded as-is, regardless of the user's browser settings.

PHP Solution

Alternatively, you can manually handle the download within PHP by adding the following code:

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");

This code:

  1. Sets the appropriate content type to indicate a CSV file.
  2. Defines the content disposition as an attachment with the specified filename.
  3. Disables browser caching to prevent the file from opening in the browser.
  4. Outputs the file to the client for instant download.

The above is the detailed content of How Can I Force File Downloads in PHP?. 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