简体   繁体   中英

Secure directory password protection without .htaccess

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM