Force Files to Download and Not Open in Browser Using Apache or PHP

By default most of the file types (eg: pdf, csv, txt, mp3, mov, mp4, jpg, png, gif, html, etc.) displayed in browser instead of download. But we can force browser to download these files instead of showing them. In this article we will explain how to force file download using either Apache or PHP.

Using Apache

Using Apache and .htaccess you can use AddType application/octet-stream to force the download of multiple extensions:


AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

The MIME type application/Octet-stream is considered to be one of the popular multipurpose application files. Generally this type is used for identifying the data that is not associated with any specific application. An Application/Octet-stream is a MIME attachment which is present in the operating system.

Using PHP

PHP allows you to change the HTTP headers of files that you’re writing, so that you can force a file to be downloaded that normally the browser would load in the same window. This is perfect for files like PDFs, document files, images, and video that you want your customers to download rather than read online. Using PHP you can take advantage of the PHP built-in readfile function:


$file_url = 'http://www.example.com/file.pdf';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
exit();

Line two forces browser to download file by defining the Content-Type. The fourth line sends the filename to save using Content-disposition. Finally the fith line outputs the file content to begin the download stream.

Victory

Using either of these techniques your files will now be forced to download.

Leave a Reply

Your email address will not be published. Required fields are marked *