morowind
morowind

Reputation: 302

Best strategy to protect downloadable files -php/mysql Apache2 server

I'll trying to figure out how to protect directory from unauthorized or not autentificated user to download files. Thank's in advance.

Upvotes: 11

Views: 13989

Answers (4)

Cybercartel
Cybercartel

Reputation: 12592

.htaccess is your best friend. Put deny from all into that .htaccess file. Or if you don't want to use .htaccess file encrypt and change all the time the download path (LOL!).

Upvotes: 2

mario
mario

Reputation: 145482

Can't find a good duplicate, but a little search will bring up results like this PHP protect a folder

There is a simple way to restrict folder access based on PHP session authorization using php. It requires creating stub files for valid authorized sesssions (and automating their deletion). In PHP you do:

if ($user_has_permission_to_download)
{
   touch("tmp/access-" . session_id()); 
}

Then a simple rewriterule+rewritecond can then serve for authorization:

RewriteCond %{HTTP_COOKIE}        PHPSESSID=(\w+)
RewriteCond ../tmp/access-%1      -f 
RewriteRule ^(.+)$  $1  [L]

RewriteRule .+  /deny   [L]

The first block permits access when the according cookie value is found and an authorization stub file exists. The second rule blocks access for anyone else.

Upvotes: 11

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14882

I'm assuming you have a users / login script somewhere that authenticates a user? Use .htaccess rewrite rules to forward the file request through a php script that checks a session variable if the user is logged in then returns the file.

Something of the elk:

.htaccess
RewriteEngine on
RewriteRule ^(.*).(pdf|exe|doc|whatever)$ some-script.php?file=$1.$2 [L]

<?php
if(loginCheck()) //function somewhere that checks session if user is logged in
{
  return fopen('../files/' . $_GET['file']); //open and return the requested file
}

This is just pseudo code to give you an idea of what you need to do. You may also have to echo the correct file headers as well.

And to stop people from just going to the files directory, I recommend putting an .htaccess file in THAT folder as well saying deny from all to stop EVERYONE from accessing it.

Upvotes: 2

Decko
Decko

Reputation: 19385

Put a .htaccess file in the directory with the files, with the following content

deny from all

Then create a script that that uses for instance readfile() to serve the file if the user is authorized.

Upvotes: 3

Related Questions