Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and Apache environment variables

Tags:

php

apache2

I want to pass an environment variable in linux to apache on start up.

export MYVAR=5 --I define my environment variable on the command line

PassEnv MYVAR --set apache to import the variable in apache config file

apachectl restart --when I restart apache I don't get an error message. However I have noticed that if I do not create the environment variable in my first step, I get a warning message, so must be working here

echo $_SERVER['MYVAR'] --i try to access the environment variable within PHP but it is not defined

I've observed that if I try to PassEnv an environment variable that already exits (one that I havn't created myself) it works fine. The SetEnv directive also works fine.

I'd really like to pass an environment variable to apache on the fly without writing it in a file. Help much appreciated.

I'm using CentOS, PHP5 and Apache2.

Thanks.

update it seems the environment variable gets passed if i invoke the apache startup directly with httpd and not use apachectl which is a shell script. I would have thought that the "export" would have exported the variable to the shell script no? I am not a linux guru so excuse my lack of knowledge.

like image 388
Simon Avatar asked May 31 '10 02:05

Simon


2 Answers

To expand on wimvds' answer above; you can change environment variables while Apache is running with the SetEnvIf module. Specifically, the SetEnvIf directive of said module.

e.g.

SetEnvIf Request_URI "^.*\/foobar.*$" FOOBAR="something"

The above example will set the $FOOBAR environment variable to "something" if the regex matches the request URI (in this case, any URI containing the word "foobar"). You can define this in your host's configuration file (usually in /etc/apache2/sites-available/mywebsite.conf or something similar).

like image 68
Wigglytuff Avatar answered Sep 19 '22 17:09

Wigglytuff


If you want the environment variable to be passed to apache, you should make sure that said environment variable is defined for the environment that apache is running in. To do that, the easiest option is to add an export MYVAR=value line to envvars (should be located in /etc/apache2) or the script that starts apache (in /etc/init.d), and add your PassEnv MYVAR where it's wanted in your apache configuration.

Restarting apache should make sure the MYVAR environment variable is passed. AFAIK you won't be able to change the value of this var while apache is running though...

Some relevant info for CentOS : http://php.dzone.com/news/inserting-variable-headers-apa&default=false&zid=159&browser=16&mid=0&refresh=0

like image 42
wimvds Avatar answered Sep 20 '22 17:09

wimvds