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
Release: 2024-12-14 01:25:10
Original
250 people have browsed it

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');
    Copy after login
  2. Output the CSV file contents using readfile():

    readfile("/path/to/example.csv");
    Copy after login

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

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!

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