Home >Backend Development >PHP Tutorial >How to Force CSV File Downloads in PHP?

How to Force CSV File Downloads in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 07:38:13224browse

How to Force CSV File Downloads in PHP?

Generating File Downloads Using PHP

Problem:

When users click a link, a CSV file opens in the browser window instead of being downloaded.

Code Snippet:

<a href="files/csv/example/example.csv">
    Click here to download an example of the "CSV" file
</a>

Web Server Configuration:

  • Ensure the web server is properly configured for serving files.

Approach 1: .htaccess Solution

To force all CSV files on the server to download:

AddType application/octet-stream csv

Approach 2: PHP Solution

To force a specific CSV file to download:

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

Notes:

  • The Content-Type header specifies the MIME type of the file.
  • The Content-Disposition header sets the file's name and disposition (e.g., attachment for downloading).
  • The Pragma header prevents caching of the file.
  • The readfile() function sends the contents of the CSV file to the browser.

The above is the detailed content of How to Force CSV 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