Hi Guys,
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
Option 1
$file_name = "test.pdf"; $mime_type = 'application/force-download'; // this is important
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.
Approach 2
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
OR
<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
Cheers
Advertisement





JC WordPress Coupon Revealer Plugin Pro License
Australian Street Names with City, State and Display Names only, Single Server License
Recent Comments