Roland Roland - 2 months ago 22
HTTP Question

Forcing to download a file using PHP

I have a

CSV
file on my server, if a user clicks on a link it should download, but instead it opens up in my browser window.

My code looks as follows

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


It's a web server normal webserver where I have all of my dev work on.

I tried someting like

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


Now the contents of my
csv.php
file:

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


Now my issue is it's downloading but not my
CSV
file it's creating a new file.

Answer

.htaccess Solution

To brute force all csv's on your server to download, add in your .htaccess file:

AddType application/octet-stream csv

PHP Solution

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