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.
To force download you may use
Content-Type: application/force-download
header, which is supported by most browsers:A BETTER WAY
Downloading files this way is not the best idea especially for large files. PHP will require extra CPU / Memory to read and output file contents and when dealing with large files may reach time / memory limits.
A better way would be to use PHP to authenticate and grant access to a file, and actual file serving should be delegated to a web server using X-SENDFILE method (requires some web server configuration):
X-SENDFILE
is natively supported by Lighttpd: https://redmine.lighttpd.net/projects/1/wiki/X-LIGHTTPD-send-filemod_xsendfile
module: https://tn123.org/mod_xsendfile/ On Ubuntu may be installed by:apt install libapache2-mod-xsendfile
X-Accel-Redirect
header: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/After configuring web server to handle
X-SENDFILE
, just replacereadfile($filePath)
withheader('X-SENDFILE: ' . $filePath)
and web server will take care of file serving, which will require less resources than using PHPreadfile
.(For Nginx use
X-Accel-Redirect
header instead ofX-SENDFILE
)Note: If you end up downloading empty files, it means you didn't configure your web server to handle
X-SENDFILE
header. Check the links above to see how to correctly configure your web server..htaccess Solution
To brute force all CSV files on your server to download, add in your .htaccess file:
PHP Solution
Here is a more browser-safe solution:
Nice clean solution: