是否有可能在.htaccess和php之间共享信息?

Hi,

is it possible to share informations between a PHP-Script and .htaccess? I was experimenting with $_ENV, but did not get it to work.

What I want to do:

Creating a login system. For every html-request, .htaccess is calling (via reWrite rule) a php and passing as parameter the original url.The PHP is testing if the user is logged in. If not: Go to the login page, if yes: Allow accessing the requested URL. That I did with php "header($url)".

The problem: This always starts a loop, because the PHP script is, after the logged-test is successfull, requesting the original url, which as again handled in the .htaccess by calling the PHP-Script.

My idea: Is there a way to set a variable in PHP, which I can access in .htaccess-condition? And is that a secure way?

Update:

As asked for, here my code.

PHP:

session_start();
$sOriginUrl = $_GET["url"];

if(!$sOriginUrl){
    return false;
}

if($_SESSION["userName"]) {
    if($_SESSION["userName"] !== null){
    header("Location: " . $sOriginUrl, TRUE, 301);
}
else {
    $aTokenizedOriginalUrl = explode("/", $sOriginUrl);
    $sLoginUrl = "/";
    for($i=0, $il=count($aTokenizedOriginalUrl); $i<($il-1); $i++) {
        $sLoginUrl = $sLoginUrl . $aTokenizedOriginalUrl[$i] . "/";
    }
    header("Location: //myurl.de/" . $sLoginUrl);
}
}
else {
    $aTokenizedOriginalUrl = explode("/", $sOriginUrl);
    $sLoginUrl = "/";
    for($i=0, $il=count($aTokenizedOriginalUrl); $i<($il-1); $i++) {
        $sLoginUrl = $sLoginUrl . $aTokenizedOriginalUrl[$i] . "/";
    }
    $_ENV["HTTP_user_logged"]="true";
    header("Location: //myurl.de/" . $sLoginUrl);
}

.htaccess:

RewriteEngine on

# This prevents the rewrite engine from looping
RewriteCond %{ENV:HTTP_user_logged} true
#RewriteCond %{forced_responsecode} 301
RewriteRule ^ - [L]

#RewriteCond %{ENV:REDIRECT_STATUS} !=""
RewriteCond %{HTTP_REFERER} !^/myurl.de/basics/validate-user-login-for-url.php$
RewriteCond %{REQUEST_URI} !^(/.*)/$
RewriteCond %{REQUEST_URI} !^(/.*)/index.html$
RewriteRule ^(.*\.html)$ /myurl.de/basics/validate-user-login-for-url.php?url=%{REQUEST_URI}&ref=%{HTTP_REFERER} [L,QSA]

Thanks for any help!!

I'm afraid what you are asking is not possible. PHP cannot share information with .htaccess because the latter is checked before PHP is executed, so the workflow is "req ->.htaccess -> php; req -> .htaccess -> php", but the only thing is preserved between requests is cookies, and no it's not secure to save the login state in the cookie, you need to use sessions, and PHP sessions are not available in .htaccess

So the solution I propose is that every file in your project which requires user to be authenticated includes a file "check_auth.php" at the beginning, then your check_auth.php can include() the login page and exit() if not logged in, or simply do nothing if the user is logged in (which means the originally invoked script continues its execution.

Hope this helps. Cheers