Quantcast
Channel: WordPress Cheat Sheets » admin
Viewing all articles
Browse latest Browse all 39

Force a Digital File Download in the Browser

$
0
0

When you click on a digital file link/URL, the browser will show/play the file if it can understand format of the file in question.

In most cases this browser behavior is fine. However, it can be a little problematic if you are trying to let your users download the digital file. The visitor will just see the file in the browser instead of the download dialogue box popping up. This is more problematic for PDF files (if you are selling an ebook and your customers can’t download the PDF file).

Fortunately, you can apply some techniques to force a file download so your visitors will see the download box when they click on a downloadable file/link.

How to Force a File Download

1. Using .htaccess Tweak

You can tweak your site’s .htaccess file to tell the web server to force a download of  particular file types from your server. For example, the following htaccess code will force a download of PDF, MP3, MP4 files:

Force PDF File Download

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

Force MP3 File Download

<FilesMatch "\.(?i:mp3)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

Force MP4 File (video) Download

<FilesMatch "\.(?i:mp4)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

2. Use PHP to Read the File and Force a Download

If you are using a content management software on your site (example: WordPress platform) then you can use a digital downloads plugin to read the file and stream it to the browser.

Generally, a digital download selling plugin (example: WP eStore plugin) will use a similar technique like the following PHP code to read the file and force a download:

$file-url = "http://www.example.com/my-downloads/my-ebook-file.pdf";
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary")
header("Content-disposition: attachment; filename=\"$file-url\""); 
echo readfile($file-url);

3. Force Download a Dropbox File

You can add the following code to the end of your drop box file URL to force a download:

?dl=1

Here is an example URL that will prompt a force download box:

https://dl.dropboxusercontent.com/b/ldjei876avm/my-ebook-file.pdf?dl=1

 


Viewing all articles
Browse latest Browse all 39

Trending Articles