Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variables for accessing in PHP when using Apache

People also ask

How do I pass an environment variable in Apache?

The most basic way to set an environment variable in Apache is using the unconditional SetEnv directive. Variables may also be passed from the environment of the shell which started the server using the PassEnv directive.

Where are Apache environment variables stored?

Apache's Environment variables are stored in /etc/apache2/envvars in Ubuntu, /etc/sysconfig/httpd in Redhat and at /etc/rc. conf in BSD.

How do I set environment variables in httpd conf?

You can get environment variables substituted in to the config file at start up with the ${ENVVAR} syntax. It's up to you to figure out how to set those variables before starting up the server. Note that these variables will persist so any scripts in languages like php will be able to read them.

Can PHP read environment variable?

There are two ways to read environment variables in PHP. One is getenv() function and another is $_ENV array. The uses of the getenv() function are shown in this tutorial.


Something along the lines:

<VirtualHost hostname:80>
   ...
   SetEnv VARIABLE_NAME variable_value
   ...
</VirtualHost>

You can also do this in a .htaccess file assuming they are enabled on the website.

SetEnv KOHANA_ENV production

Would be all you need to add to a .htaccess to add the environment variable


Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}
</VirtualHost>

Then finally....

service httpd restart;

If your server is Ubuntu and Apache version is 2.4

Server version: Apache/2.4.29 (Ubuntu)

Then you export variables in /etc/apache2/envvars location.

Just like this below line, you need to add an extra line in /etc/apache2/envvars

export MY_ENV_NAME=myEnvValue