Subscribe

RSS Feed (xml)

File Download Security

Want to prevent people from linking to your downloads? This script will force a page to be loaded before the download starts. HTML header statements are used to trigger the download of the file. PHP is used to push the file to the browser.

Principles

HTML headers must be sent before any output is sent to the browser. PHP uses the header function to pass raw HTML headers. For this example we're going to get the filename from the URL www.yourdomain.com/download.php?file=download.zip.
$dir="/path/to/file/";
if (isset($_REQUEST["file"])) {
    $file=$dir.$_REQUEST["file"];
    header("Content-type: application/force-download");
    header("Content-Transfer-Encoding: Binary");
    header("Content-length: ".filesize($file));
    header("Content-disposition: attachment; filename="".basename($file).""");
    readfile("$file");
} else {
    echo "No file selected";
}
 ?>
We started with setting the directory where the files to be downloaded are located in $dir. Be sure not to use in $dir. Then we checked to make sure a filename was specified in the request. If a file was specified then we set $file to the path to the file and the filename. Now that the prep work is done its time to send the file to the browser.
The first header statement tells the browser to expect a download. The next two header statements tell the browser the format of the data and the size of the file respectively. The last header statement tells the browser the name of the file. Finally the readfile statement sends the file to the browser.
On the next page we'll start showing some examples on how to use this.

Related Posts with Thumbnails