Downloading Files in PHP for Fun and Profit

I recently had to setup a page where users could download files. You’d think such a task would hold few secrets for someone who architected a download site. Well, that’s how much you know.

Like many programming tasks, you meet it head-on, on the field of battle; you grab it by the horns and wrestle it to the ground. Victorious, you move on, and quickly forget the finer nuances which thrilled your sense of challenge and elegance. Luckily for you, I’ve started documenting these little trysts in this blog.

Downloading files in your PHP code should look something like this:

header('Content-disposition: attachment; filename="myfile.pdf"');
header('Content-type: application/pdf');
readfile('myfile.pdf');

If your filename has special characters or spaces in the name, you need to add double quotes around the filename to allow the webserver and browser to properly handle the name. Otherwise, the filename gets truncated at the first space character. Also, using single quotes rather than double quotes will interpret the single quotes as part of the filename.

The content-type header contains the MIME media type. In the example above it’s a PDF, but it could be an image, text file or anything else.

Here are some resources I found which helped with figuring it all out:

Filenames with spaces are truncated upon download

RFC 2046: Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types

Wikipedia: Internet Media Types

Ideally we could specify that it would either download or open the file using a specific program, but that would leave users open to security issues from blackguards. It’s up to the client to decide how to handle file downloads; and, of course, with modern browsers, users can configure such behaviour with appropriate plugins.

Leave a Reply

Your email address will not be published. Required fields are marked *