Force download files and not open in browser

Are you tired of asking your users to right-click and “save link/target as” in order to download your .pdf (or game generated) files? Find out how to force download those files in any modern browser.

There are situations where you might want a hyperlink leading to a file to trigger a “Save As” dialog in browser instead of having the browser trying to read/open that file.

This usually reigns true for PDF downloads or just obscure file types, such as files generated from various computer games.

For my case, I had some game generated file types I wanted to force download on them because a lot of users were reporting trouble getting the files as their browser was trying to read the files. I had to keep asking them to right-click on the download link and “save target/link as” for that to work properly.

The Apache Solution

So today I just got tired of advising for right-clicking and did a quick research how to force download those files on single left click for any modern browser. My sites are all using Apache, so the solution is cropping up to adding one line in the .htaccess file.

Here’s the code you need to add in your .htaccess:

AddType application/octet-stream .pdf

Replace .pdf with the file type in question. If you want to add multiple file types to this rule, you can either add a new line of the same and change the file extension or there’s a shortcut:

AddType application/octet-stream .pdf .doc .etc

Source: CSS-Tricks

The PHP Solution

You could have a PHP wrapper for download links that takes an argument and then reads the file (assuming local files) and before outputting the file to the user you send headers with the file type.

Example:

// We'll be outputting a PDF
header('Content-type: application/pdf');

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

// The PDF source is in original.pdf
readfile('original.pdf');
?>

Source: PHP.net

The HTTP Header Solution

You have to include the following header in HTTP response of the file to be downloaded:

Content-Disposition: attachment; filename=filename.ext

Where filename.ext is the filename you want to appear in “Save As” dialog (eg. mycv.pdf).

You have to keep the following in mind:

  • The filename should be in US-ASCII charset.
  • The filename should not have any directory path information specified.
  • The filename should not be enclosed in double quotes even though most browsers will support it.
  • Content-Type header should be before Content-Disposition.
  • Content-Type header should refer to an unknown MIME type (at least until the older browsers go away).

Source: JTricks

Choose what’s best for you

Alright, I’ve presented you with the different ways you can achieve forcing download of files from links leading to them. If there’s a way I’ve missed please comment and I’ll update the post.

Happy coding!

Leave a Reply

 
 

RSS Updates