Force download on click in PHP

Many newbie web developers struggle with this, so I thought I’d write a quick tutorial on how to force a user’s browser to download a file when a link is clicked, instead of the file (such as a pdf) opening within the browser.

The way we are going to do this is with HTTP headers. Before a browser receives a web page from the web server, the server sends HTTP headers to give the browser more info on the data that is to come. We use these headers to tell the browser that the data is a specific type of file, that it has to be downloaded instead of opened within the browser itself, and what the name of the file is going to be once the user has saved it to their computer.

First of all, just build your link like you always would:

<a href="downloadfile.php">Click here to download</a>

The file that you reference in the link (downloadfile.php) is not the file which you want the user to download however, but is actually a script which is going to tell the user’s browser to download another file which exists on the server. The user, when clicking on the link, isn’t even going to be directed away from the page they are currently on, and will only see a download box!

The code in this PHP file is something like the following:

// The user will receive a PDF to download
header('Content-type: application/pdf');

// File will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The actual PDF file on the server is source.pdf

That’s it.

So what does it all mean?
The Content-type header specifies what type of file is to be downloaded, specified by a mime type.
The Content-Disposition header specifies a new filename for the file which is to be downloaded.
The readfile line is not a header being sent, but a PHP call that gets all the data from a file and outputs it. The argument you pass to the readfile function is the location of the actual pdf file to be downloaded.

Easy as that!

Leave a Reply