Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables are not passed from .htaccess to 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:

  1. mod_env is not installed/enabled by the host. Can't be, because then SetEnv would not be recognized and I'd get a 500 while processing the .htaccess.

  2. AllowOverrides in httpd.conf for this directory doesn't include FileInfo. Can't be, because then Apache would throw an error "SetEnv not allowed here" when encountering the SetEnv directive and I'd get a 500 again.

  3. variables_order in php.ini doesn't include 'E'. This would explain the $_ENV superglobal being empty (which it is), but not why getenv() doesn't return values for these variables.

  4. Entire environment is screwed up. Can't be, because getenv('PATH') and getenv('SERVER_NAME') still return valid values.

At this point I'm at a loss as to what configuration could be causing this.

like image 671
nitwit Avatar asked Jun 12 '13 18:06

nitwit


2 Answers

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.

like image 54
Brandon Rohde Avatar answered Oct 10 '22 23:10

Brandon Rohde


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_.

like image 45
Phil Perry Avatar answered Oct 10 '22 22:10

Phil Perry