Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top