PHP Force Download File in Browsers

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

  1. $file_name = "test.pdf";
  2. $mime_type = 'application/force-download'; // this is important
  3. header('Pragma: public');
  4. header('Expires: 0'); // We tell browser no to cache anything
  5. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  6. header('Cache-Control: private',false);
  7. header('Content-Type: '.$mime_type); // Content-Type is now set to application/force-download
  8. header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
  9. header('Content-Transfer-Encoding: binary');
  10. header('Connection: close'); readfile($file_name); // reads a file from start to end
  11. 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.

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

 

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Speak Your Mind

*

CommentLuv badge