Sometimes we have to do it, reason can be any. We want user to download a file rather than opening it in browser. For that to happen browser have to know what to do.
Here is a very useful code snippet that I use to force browsers to download file to disk rather than to open in browser for supported format.
Now there are couple of ways to force download a file, first lets take a look at this code snippet
Say you want a PDF file to force download
- $file_name = "test.pdf";
- $mime_type = 'application/force-download'; // this is important
- header('Pragma: public');
- header('Expires: 0'); // We tell browser no to cache anything
- header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
- header('Cache-Control: private',false);
- header('Content-Type: '.$mime_type); // Content-Type is now set to application/force-download
- header('Content-Transfer-Encoding: binary');
- die(0); // nothing else should be written to stream
If you try to use above code snippet then the file test.pdf in my case does not open in my browser but infact it is downloaded.
You can change the filename to anything you like.
You can also do this as a global setting for any file you think should be available for download.
You can use apache configuration to do this, either make change in your httpd.conf or add these lines to your .htaccess file
AddType application/octet-stream .avi AddType application/octet-stream .mpeg AddType application/octet-stream .mp4 AddType application/octet-stream .pdf AddType application/octet-stream .docx
<FilesMatch "\.(avi|mov|mp3|doc|pdf)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>
You can add or remove file extensions to above list.
This way you can control your force downloads globally on your site.
Now thing is that second method should only be used when you are 100% sure that you want certain file types to be downloaded from your site. Else Approach 1 should be used.
I generally use approach 1 because that way I’ve control on what file I want user to download.
I hope this helps