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

How to Force CSV File Downloads in PHP?

Barbara Streisand
Release: 2024-12-19 07:38:13
Original
245 people have browsed it

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

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

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

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!

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