1

I want to assign a variable from within PHP and make said variable available to my .htaccess file so that it can use the value to, for example, deny or allow access.

Example index.php file:

<?php
  session_start();
  $_SESSION['REMOTE_USER'] = 'valid';
  $_SERVER['REMOTE_USER'] = 'valid';
  $_ENV['REMOTE_USER'] = 'valid';
  putenv('REMOTE_USER=valid');
  print 'You are allowed.';

Here is one example of what I've tried inside the .htaccess file (which is in the same directory as index.php):

# Doesn't work... Always denied.
SetEnvIf Remote_User valid allowed
SetEnvIf Remote_User notvalid disallowed
Deny from all
Allow from env=allowed

Is there a way to allow or deny access through .htaccess based on values provided by PHP?

jerdiggity
  • 3,655
  • 1
  • 29
  • 41
  • The only remotely feasible option (if you really need that approach) is to create temporary state/lock files in conjunction to just setting a PHP session variable. Their existence could then be probed by extracting the ID from `%{HTTP_COOKIE}` and a simple RewriteCond. – mario Dec 07 '14 at 01:21

3 Answers3

4

The .htaccess file is run before the PHP script is run. In other words, what you are describing is not possible.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
2

.htaccess is read by the server before PHP file, so what you seek is quite impossible.

On the other hand, you may set PHP variables inside .htaccess

SetEnv HTTP_MY_VARIABLE "my value"

Maybe that would help you somehow

Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
2

As the other answers already state, you are having a chicken/egg problem: the fact that the PHP is running means the .htaccess saw no reason to forbid it, and its work is done.

Denying access to a page in PHP, where you should be doing more complex authentication and authorization stuff, is trivial though:

if($myUser->shouldNotBeHere()) {
  header('HTTP/1.1 403 Forbidden');
  die('Access denied!');
}

This looks the same as an Apache-level deny to the browser.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136