PHP Force File Download Script
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'] . "/files/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 want to be wary of is 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. Restricting all files to a specific directory and scrubbing the file parameter passed to remove any references to folders would be a good place to start.
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_ref=123 (perhaps a primary key from a DB table)
- /download.php?file_ref=k1jh44 (even better – 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.