I have been trying to figure this one out also, and unfortunately I don’t think it’s possible. Here’s why:
What we want to do is basically replace the HTTP WWW-Authentication method with something serverside. What we need is a way to supplant the information that would normally be sent by a browser ( Specifically, the Authorization header ) to the Webserver along with the GET request, with our own authentication information. Unfortunately, I don’t see any way of doing this with the existing PHP function-set or Apache modules. Special hooks would also need to be designed in Apache to supply it with a username/password for the mod_auth module from an external source. This would not be a simple task as I’m sure many security issues would need to be taken into consideration.
That leaves us with 2 choices for combining Apache’s .htaccess security with our own website’s security:
1) Send our own 401 header with WWW-Authenticate headers, get the results, validate them with our database and the htaccess privileges will be set at the same time. Many examples of this exist on this site, and others – including the PHP documentation. ($PHP_AUTH_USER and $PHP_AUTH_PW are only set by PHP after a successful Apache htaccess request has been made. Setting these variables manually ourselves isn’t going to propagate them back to Apache.)
2) Set up a daemon or scheduled program to populate htpasswd files for each protected directory (depending on content or subscribed services, perhaps) with the usernames and crypt()ed passwords from our custom user database. How you want to do this is up to you. Since the htpasswd file uses the standard system crypt() function (and can also use MD5, if you’ve set up your server that way) - as long as you used the same scheme to protect your users passwords, all that is needed is a simple select from the database outputted properly to an htpasswd text file. This process will still require the user to re-enter his same login/password when he first accesses the protected area.
Neither of these offer an elegant solution to content protection, however this is security and if your files are important or valuable, elegance will have to take second place. Out of the two I have seen the second one in use the most, and makes the most sense to me.
I’m sure the PHP Dev team could develop a function that would pass this information securely to the Apache server – perhaps we could all encourage them too. Until then, we’re stuck with the old-fashioned htaccess method.
Don’t forget, there are many other ways of protecting your content from being harvested by anyone, but you have to be creative – i.e. create softlinks to files outside the general HTML tree as they are requested and clean them up later. Some websites actually dynamically allow individual clients IP level access to certain areas only after they have logged in, disabling the IP’s later, after a timeout period has expired.
Joe T.