Php – How to secure a directory in Apache using a PHP session

apache-2.2authenticationPHP

I have a site that uses PHP session for authentication. There is one directory that I would like to restrict access to that does not use any PHP, it's just full of static content.

I just don't know how to restrict access without every request going through a PHP script. Is there some way to have Apache check the session credentials and restrict access like Basic Auth?

Best Answer

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:

Related Topic