Force file to download

by leon on October 28, 2008

A common issue with modern browsers is the fact that they have the ability to open many file types by default. This isn’t usually a problem, unless you want to make sure that a file is downloaded to a user’s desktop. You could zip the file, which usually forces a download, but what about times when zipping something is just an unecessary step (such as a vCard).

A simple trick is to use the script below to force the browser to download the file.

 
if ($_REQUEST["filename"] != “”) {
$filename = str_replace(“../”, “”, $_REQUEST["filename"]);
if ($filename != “”) {

/*
this is where you set the base path and the file for security reasons.
*/
$file = dirname(__FILE__) . “/files/” . $filename;

if (file_exists($file)) {
header (“Content-type: octet/stream”);
header (“Content-disposition: attachment; filename=” . str_replace(” “, “_”, basename($file)) . “;”);
header (“Content-Length: ” . filesize($file));
readfile($file);
die();
}
else {
//add function if file is not found here
}
} else {}
} else {}

To make it work add the above script to a page called something like download.php. Then add the name of the file as a querystring parameter as below:

<a href=”download.php?filename=podcast1.mp3″>Download File</a>

Leave your comment

Required.

Required. Not published.

If you have one.