File Download Security

3 posts Page 1 of 1
Contributors
User avatar
wrighty1986
VIP - Donator
VIP - Donator
Posts: 119
Joined: Sat Sep 12, 2009 11:55 am

File Download Security
wrighty1986
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.
Code: Select all
<?  
$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.
MySQL Download Tracking
One application of this would be to track information about file downloads. Here we're going to track the number of downloads and when the last download occurred. We're going to store the information in a MySQL database. Below is the structure of the table.
Code: Select all
CREATE TABLE filestats (
   fileid INT NOT NULL auto_increment,
   filename TEXT,
   downloads INT NOT NULL,
   lastdownload DATETIME,
   primary key (fileid)
);
The fileid is just an auto incrementing number used to keep track of the database. Filename will be the field we search with. Downloads and lastdownload are the fields used for keeping statistics.

Insert the following code after the if (isset($_REQUEST["file"])) { statement. This code will connect to the MySQL database and update the file stats. PHP has a strong built in function library for MySQL.
Code: Select all
<?  
$db=mysql_connect($mysql_host,$mysql_login,$mysql_passwd) or die(mysql_error()); 
mysql_select_db($mysql_database); 
$query=mysql_query("select * from filestats where filename='".basename($file)."' LIMIT 0,1") or die (mysql_error()); 
$fileexist=@mysql_num_rows($query)); 
$now=date("Y-m-d G:i:s"); 
if ($fileexist>0) { 
    $updatequery=mysql_query("update filestats set downloads=downloads+1, 
    lastdownload='$now' where filename='".basename($file)."'") or die (mysql_error()); 
} else { 
    $addquery=mysql_query("insert into filestats (filename,downloads,lastdownload) 
    values ('".basename($file)."','1','$now')") or die (mysql_error()); 
} 
 ?>
The date function is used to set the current date and time. Here it will be displayed in the YYYY-MM-DD HH:MM:SS which is the format of the MySQL datetime format.

In this segment we connected to the MySQL database and updated the download statistics. First mysql_connect connected to the database passing the connection parameters in the order of host, login, and password. Then we selected which MySQL database we wanted to use with the mysql_select_db statement. Once we have the connection completed we check to see if the table holds a record for the file. The first mysql_query searches the database for a record with the filename of the file being downloaded. Mysql_num_rows determines the number of results returned from the query. Here we preceded the mysql_num_rows with a @ to prevent it from returning errors if the query results were empty.

If there was a result from the query $fileexist will be greater than 0 so we update the database. To do this we use a MySQL update query. If there wasn't a result returned an insert query will be used instead of an update.

Other Uses
Other uses for this include downloading of subscription based content. To do this wrap the code in a check of credentials. This is easily done with an if (<credentials check>) { and place the code inside the if statement. A popular method of storing credintials is using a mySQL database and granting sessions or cookies to users who supply valid credentials. These methods provide easy security for People selling E-Books, downloadable software, Intranet file downloads, etc.
Back Aegean sorry not been on i.v just been moving.
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

Re: File Download Security
mandai
Did you ask them if you could use their tutorial?
Last edited by mandai on Sun Apr 29, 2012 9:30 pm, edited 1 time in total.
User avatar
wrighty1986
VIP - Donator
VIP - Donator
Posts: 119
Joined: Sat Sep 12, 2009 11:55 am

Re: File Download Security
wrighty1986
its of ther mate an emaild the admin e sed ye i can post elcwher.
Back Aegean sorry not been on i.v just been moving.
3 posts Page 1 of 1
Return to “Tutorials”