PHP. Protect File From Unauthorized Access

vicnumb Oct 12, 2012

Oct 12 2012 Published by under PHP & MySQL, Tricks

Selling downloadable products you perhaps faced a problem: Unauthorized download.
You upload a file, sell it several times, then notice that your file is being accessed by much more people than it was expected to.

As a solution you can send file through email, but in nowadays many people expect instant download, so refunds will start bothering you.

In fact there is a rather simple php solution allowing downloads to authorized people only.

1. Protect your downloads folder.

Create a file named: .htaccess
Paste the code below to your htaccess file and upload it to your downloads folder.

order deny,allow
deny from all

This way was stopped the direct access to file.
Try to download it via direct url:
http://yourwebsitename/downloads_folder/file_name
From the other side, all scripts installed on your server have access to file. They can open it and operate with file data.

2. Assign download credits to user after a certain action:

– after a successful payment, use a SESSION variable.
– by a database record allowing user 1-2-3-multiple trials to download the file.

$download_credits = true; //replace this variable with session variable or DB credits
if($download_credits){
  $filepath = 'path_to_file';
  $filename = 'file_name';
 
  //call download function
  download($filename);
  unset($download_credits); //unset session variable or DB credits
}

3. File Download PHP Function

file download php script

No responses yet

Leave a Reply