views:

655

answers:

2

Hi, I was going to use .htaccess to password protect a directory for a php script I'm writing, as I do not trust my PHP skills to create a secure login, but I found out you cannot use relative paths for AuthUserFile and I could not generalize this.

If you could direct me to a secure PHP login script to password protect a directory I would be very grateful. Thanks.

A: 

You can use absolute paths to the AuthUserFile, and arrange to put that file in a place not accessible to the web server. I've done that for many years. Works fine.

Dave W. Smith
The thing is, if I'm distributing this I do not know where the user is going to place the script or what OS they are on. So I don't think I can use .htaccess?
blake
You can still use .htaccess (and .htpasswd). There's rule in the default Apache config (for Apache2, at least) to block access to any file named .ht*
Dave W. Smith
+1  A: 

One thing you can do is keep all your "secret" files in a directory outside of the server's webroot. All access to these files can then be routed through a single PHP-script inside your directory. Something like this:

http://www.example.com/protected-directory/access.php?file=/foo/document.doc

With a directory structure such as this:

+--+ /server_root
   |
   +--+ /web_root
   |  |
   |  +--+ /protected-directory
   |     +-- access.php
   |     +-- access-denied.html
   |
   +--+ /protected_root
      |
      +--+ /foo
         +-- document.doc

In your access.php you would do something like this:

$file = $_REQUEST['file'];
if ($user->hasAccessTo($file)) {
    readfile("/server_root/protected_root/$file");
} else {
    readfile('access-denied.html');
}

Now, you have to be careful that you make sure nobody screws with your file-parameter and passes something along like "../../../etc/passwd". Also, you probably want to make sure you send the correct headers in the above example, I omitted that for reasons of clarity.

n3rd