PHP Force File Download Script
15 Nov 2007 - Simple script for forcing the download of a file using PHP header.
For a recent eConnected client, we were required to have a link to a vcard that could be downloaded. The problem was that this is just a pure text file and as such is typically just opened in the browser.
It took me quite some time to locate help on this so I thought that it would prudent to share them.
The simple version can be done in just 3 lines of code:
header("Content-disposition: attachment; filename=download_filename.vcf");
header("Content-type: text/x-vCard");
readfile( $_SERVER['DOCUMENT_ROOT'] . "/content/pages/original_filename.vcf");
The above example is for a specific file. The likelihood is that you will require a more generic example.
Generic
Adding flexibility to the script is fairly easy. All you need to do is pass a reference to the file and let PHP figure out the file type (unfortunately you can't always do this using PHP itself (it depends on the server setup), so your best bet will be to use something like the file extension to match the mime-type).
Securing the file
The one thing you don't want to do is to create the file download by passing a file reference in the query string, for example:
- /download.php?file=/dir/filename.txt
The security issue here is that this gives someone an easy way of downloading any file in your website directory. A few guesses and someone might have your database access details.
If you are downloading files previously uploaded and stored in a database (at least a reference to it) then you could pass a key that relates to the database entry.
- /download.php?file=123 (perhaps a primary ker reference for a database table)
- /download.php?file=k1jh44 (even better, an encrypted reference of some sort)
This keeps the source file a bit more anonymous and will also restrict the files that can be downloaded by the end user.
Add Comment
Unfortunately I have had to disable comments temporarily as I am getting too much comment spam. By all means drop me an email (hello at rickhuby dot com) if you want to get in touch about anything. Hopefully I'll magically discover oodles of time laying around and get this sorted quickly.