环境变量不会从.htaccess传递给PHP
I am trying to pass an environment variable from .htaccess through to PHP. This works just fine on my local WAMP server, but on the server where my website is hosted, it fails without reason.
Here's my test configuration:
.htaccess:
SetEnv TEST_VARIABLE test_value
test.php:
<pre>
getenv('TEST_VARIABLE') = <?php print getenv('TEST_VARIABLE'); ?>
getenv('REDIRECT_TEST_VARIABLE') = <?php print getenv('REDIRECT_TEST_VARIABLE'); ?>
</pre>
On my local server, getting test.php correctly returns:
getenv('TEST_VARIABLE') = test_value
getenv('REDIRECT_TEST_VARIABLE') =
But on the production server, it returns:
getenv('TEST_VARIABLE') =
getenv('REDIRECT_TEST_VARIABLE') =
Things I've ruled out:
mod_env
is not installed/enabled by the host. Can't be, because thenSetEnv
would not be recognized and I'd get a 500 while processing the .htaccess.AllowOverrides
inhttpd.conf
for this directory doesn't includeFileInfo
. Can't be, because then Apache would throw an error "SetEnv not allowed here" when encountering theSetEnv
directive and I'd get a 500 again.variables_order
in php.ini doesn't include 'E'. This would explain the$_ENV
superglobal being empty (which it is), but not whygetenv()
doesn't return values for these variables.Entire environment is screwed up. Can't be, because
getenv('PATH')
andgetenv('SERVER_NAME')
still return valid values.
At this point I'm at a loss as to what configuration could be causing this.
I don't think using setenv normally works in .htaccess. It's a shell script command (bash, C shell, etc.). If your server does support setenv, according to https://kb.mediatemple.net/questions/36/Using+Environment+Variables+in+PHP#gs you need to have the variable name start with HTTP_.
If you are running your home server on a Mac or have suEXEC enabled, there are security measures in place to strip any non-http environment variables that are defined, therefore they won't appear in $_ENV['APPLICATION_ENV']. You CAN, however access these through a native PHP function to get the same thing.
$var = apache_getenv('APPLICATION_ENV');
That function will get any environment variable defined with SetEnv in your .htaccess file, or any environment variable that is set in php.ini, even if PHP removes these from the $_ENV variable.
You could then define the environment variable within PHP if you want, although not recommended.
$_ENV['APPLICATION_ENV'] = apache_getenv('APPLICATION_ENV');
Or the better solution: just define a global:
define('APPLICATION_ENV', apache_getenv('APPLICATION_ENV'));
Once you do that, it should work as desired.