php Tutorials
Creating An RSS Feed With PHP And MySQL
Retrieving XML With Curl and SimpleXML
Using curl to Query Remote Servers
MySQL Basics
PHP mySQL Voting Booth
File Download Security
PHP Fundamentals

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. For this example we're going to get the filename from the URL

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.

On the next page we'll start showing some examples on how to use this.

 1 2 3  >> MySQL Download Tracking
New Content

Related Information
MySQL Basics