PHP Authentication and .htaccess

10:55.57 - Friday 30th September 2005   (Link to This Entry)


I'm in the process of creating a client lounge for a website, and I ran into the problem of how to keep everyone from seeing other people's work in progress. I wanted a directory structure something like this...
  login.php
  login2.php
  clients/
    tom/
    dick/
    harry/
...where tom/, dick/ and harry/ were protected with a .htaccess file so that I could just plonk stuff into them without worrying about extra coding. I wanted the user to enter a username and password into a form on login.php and have login2.php set the Apache login details so that the standard login prompt wouldn't appear. Login2.php would then redirect to the relevent client subfolder which was the same as the username.

The problem was not having a clue how to actually get this to work. I had a natter with Loki about it and we couldn't think of an elegant way to do it to save our lives. In the end I resorted to what I consider a bodge, but at least it's one that works.

In each client folder there is a file called DO_NOT_DELETE.php which accepts a username in the querystring and redirects to http://domain/folder/clients/$user/ - the top of the folder that it's actually in. The trick is to call this file from login2.php (assuming the details are correct) using the horrible http://$user:$pass@domain/folder/clients/$user/ approach.

Because login2.php calls it in this manner, it sets the Apache login details and thus bypasses the normal user/pass prompt. DO_NOT_DELETE.php then redirects back to the root of the client's folder so that the user and pass are no longer visible in the address bar, and we can load index.php or whatever. It's horrible, but it works.

Update:
And of course, this doesn't work in Internet Explorer because it was blocked to help prevent phishing attacks - what a crock!

I've given up on the custom login page and instead I've got a structure like this:
  login.php
  login2.php
  clients/
    tom/
    dick/
    harry/
The major difference now is that clients/ it protected with .htaccess as well, but it's password list contains details for tom, dick and harry whereas the tom/ dick/ and harry/ folders only allow those users in. Within clients/ there's an index.php which simply redirects to the relevent folder based on the value of $_SERVER['REMOTE_USER'], which is only set once you've successfully authenticated.

Pros: No need for a 'DO_NOT_DELETE.php' file in each client folder.
Cons: No custom login page.


[ 0 comments pending ]