Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing to download a file using PHP

Tags:

http

php

download

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 normal webserver where I have all of my development work on.

I tried something 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 creates a new file.

like image 432
Elitmiar Avatar asked Sep 23 '09 12:09

Elitmiar


People also ask

How can I force download a zip file in PHP?

For force download, you have to set the header correctly. When you are setting the header for download the Zip file that time <coce>Content-type and Content-Disposition correctly. In Content-Disposition , add the attachment, it will suggest the browser to download the file instead of displaying it directly.


1 Answers

.htaccess Solution

To brute force all CSV files 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"); 
like image 51
robjmills Avatar answered Oct 18 '22 19:10

robjmills