Home >Backend Development >PHP Tutorial >How to Force CSV File Downloads in PHP: A Header and `.htaccess` Approach?

How to Force CSV File Downloads in PHP: A Header and `.htaccess` Approach?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 01:25:10251browse

How to Force CSV File Downloads in PHP:  A Header and `.htaccess` Approach?

Forcing CSV File Download with PHP

When a CSV file opens in a browser window upon clicking a link instead of downloading, modifications to the code and server settings are required.

The suggested approach in question 2, creating a separate PHP file (csv.php) to handle the download, should work as intended. However, an alternative approach is to use the header() and readfile() functions directly in the HTML page. This method ensures the actual CSV file is downloaded.

PHP Solution

  1. Set the appropriate headers:

    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="example.csv"');
    header('Pragma: no-cache');
  2. Output the CSV file contents using readfile():

    readfile("/path/to/example.csv");

.htaccess Solution

As a more universal solution, you can force all CSV files to download using a modification in the .htaccess file:

AddType application/octet-stream csv

By implementing one of these solutions, you can successfully force CSV files to download instead of being displayed in the browser window.

The above is the detailed content of How to Force CSV File Downloads in PHP: A Header and `.htaccess` Approach?. 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