Saturday, June 10, 2006

File Download Security

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.
HTML headers must be sent before any output is sent to the browser. PHP uses the header function to pass raw HTML headers.

if (isset($_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)."\"");
} 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.

No comments: