Archive

Posts Tagged ‘download link’

How to Make a Link Automatically Start to Download a File Using Content-Disposition Header

July 21st, 2010 No comments

Sometimes we want to have a link to a file that rather than open the audio file/image/pdf and display in the browser, to have it automatically download the file to the user’s machine without requiring them to right click and “save as.” Some call this a “force download” link. The way this is done is to modify the headers of the page.

You might be looking for something to put into the <a > tag, but unfortunately it’s a little more complicated than that. Instead of pointing the link directly to the file, point it to a php file with an argument for the file to download. Something like this:

<a href='download.php?file=test_file.pdf'>Download</a>

In the download.php file, a couple headers need to be defined in order to ensure the browser handles it correctly (and doesn’t take matters into its own Preferences). You do this in PHP like this:

<?php

header("content-type: application/pdf");    // Tell browser what kind of stuff you're sending; here, render a PDF

header("content-disposition: attachment; filename=name_to_be_saved_as.pdf"); // Tell browser how to treat it; here, directly download

?>

For different types of files, you should define the content-type appropriately.  Here’s a good reference for the content-type string needed for the kind of file you’re sending  http://www.w3schools.com/media/media_mimeref.asp. You can set the filename with the ‘filename’ attribute after Content-Disposition. Note the use of the  ’=’ instead of the ‘:’ in assigning the filename.

Then you need to send the content itself:

<?php  echo file_get_contents("test_file.pdf");  ?>

Be careful not to echo anything other than the content of the file you want to force-download. That can throw errors.