Force Files to Download Instead of Showing Up in the Browser

Sometimes you may have noticed that when you click on a download link, the file shows up in one browser while in some other browser it gets downloaded. Internet Explorer will usually try to show Microsoft Word files (doc and docx) in the browser, while most other browsers will download it.

If the browser supports a file it shows up the file else it downloads the file. Image files like png, gif, jpg almost always show in the browser. Archive files like zip, tar, and gzip almost are always downloaded.

To force certain file types to be downloaded, you can follow the following options:

Option 1: Zip Creation

A simple solution is to put your file inside a zip file and create a hyperlink to this zip file. Browsers cannot read zip file so it will force a download.

Option 2: Apache Web Server


Add the following lines to your .htaccess file

<FilesMatch "\.(mov|mp3|jpg|pdf)$">

ForceType application/octet-stream

Header set Content-Disposition attachment

</FilesMatch>

These line force download of mov, mp3, jpg and pdf file. You can add or remove file types as per your requirements. This .htaccess file needs to be placed in your download files dirctory

You may need to load mod_headers in Apache2 for this to work.

Assuming you have root access it can be done as follows:


# a2enmod headers

# /etc/init.d/apache2 reload

Option 3: PHP Code


<?php

// 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');

?>

Leave a Comment

Back to top