Force download using PHP

A force-download script can give you more control over a file download than you would have providing a direct link. Using a force-download script, you can:

Download image file

Download pdf, flash, mp3 etc. files

Validate that a person is logged in

Increment a counter in a text file

Connect to your database and log IP information, increment a counter, and so on.

For instance, say you have an mp3 of your newest hit single that you would like to share with site visitors. You can link to this file by simply creating a link:

The problem with this method is that most browsers have the capability to play an mp3 file. Therefore, they will automatically load up their Quicktime, etc. plug-in and start progressively downloading the file. This is not going to get that file on your site visitor’s hard drive like you originally intended. Well thanks to the wonderful language of PHP, we can quickly change this behavior or our site visitors’ browsers.

First thing we need to define the path of the file

$file = “resume.doc”;

Second thing we need to define the header

header(“Cache-Control: public”);

header(“Content-Description: File Transfer”);

header(“Content-Disposition: attachment; filename=$file”);

header(“Content-Type: application/zip”);

header(“Content-Transfer-Encoding: binary”);

Now that we have all of these headers set, what do we do? Well simply put, we open the file using the readfile() function. This will actually be place inside of the else curly brackets.

readfile($file);

 The Complete code will be:

 <?php

$file = resume.doc;

header(“Cache-Control: public”);

header(“Content-Description: File Transfer”);

header(“Content-Disposition: attachment; filename=$file”);

header(“Content-Type: application/zip”);

header(“Content-Transfer-Encoding: binary”);

// Read the file from disk

readfile($file);

?>

For more information click here

Share This Post

Post Comment