How to secure a directory in Apache using a PHP session

Solution 1:

Unless you've changed the settings, PHP session data is stored in a variation on its own serialize() format in a temporary directory, and it's not easy to get at that without using PHP itself.

unfortuantly, you appear to want the speed of static served files while dynamically authorising each request, which are not really compatible goals. You might comprimise by having a super-light PHP script which you then use mod_rewrite to rewrite requests to files within it to, which passes though things that are fine. Super simple example:

.htaccess:

 RewriteEngine On
 RewriteMap auth prg:auth.php
 RewriteRule (.*) ${auth:$1}

auth.php:

#!/usr/bin/php
 <?PHP
 set_time_limit(0); # This program needs to run forever. 
 $stdin = fopen("php://stdin","r"); # Keeps reading from standard in
 while (true) {
        $line = trim(fgets($stdin));
        if (isset($_SESSION['USER_LOGGED_IN'])) {
                echo $line\n";
        } else {
                echo "authfailed.html\n";
        }
 }

notably, that PHP script is running forever, so you'll need to restart apache if you change it, I think.

This is all untested, but that's roughly the direction I think you'd have to go in.

References:

  • http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteMap
  • http://onlamp.com/pub/a/apache/2005/04/28/apacheckbk.html
  • http://www.wellho.net/resources/ex.php4?item=a603/andy

Solution 2:

If you had a particular cookie you can expect, then you can test for its absence with mod_rewrite and give a 403 Forbidden.

RewriteCond %{HTTP_COOKIE} !LoggedIn=true
RewriteRule .* - [F,L]

But, if anyone knew that they needed a cookie set with "LoggedIn=true", then they could easily get around your "protection".

A PHP session is specific to PHP. Apache has no way of using any info in a PHP session. You would have to have some authentication module specifically for doing the session verification.

What I've seen most people do is have a PHP script handle the serving of the static content in that it gets the request, verifies the session, reads in the file and sends the content out with the appropriate MIME info.

Solution 3:

The conventional solution for that problem is to redirect every call on that folder to a php file, which checks the user permissions, and after that it reads the file, and send it to the output stream or redirects the user to the "no permission" site. For example...

Another tricky way to protect you files is to generate a token from the session_id, and a static salt (and optianally from the static file path), and check it by the file accessing. So you have to regenerate that token in you htaccess file. I don't know whether it's possible only with .htaccess, or you have to use php for that. I found a similar solution here. I'm 99% convinced, that the md5 is not a built in mod rewrite feature.