Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make environment variables available to Apache, started as a service?

I know that adding some environment variables to /etc/environment will make them available system-wide, adding them to /etc/profile , ~/.bashrc or equivalent, will make available to a specific user... all this however applies to interactive sessions. When Apache is started as a systemd service, it is a non-interactive session so it does not see those environment variables. Can I have Apache parse an .env file which contains lines like

env1=foo
env2=bar
...

and then could access them in my PHP code with $_SERVER['foo'] , etc. Of course, I would like to achive the same for other systemd services too, so is there any specific file that provides env variables for services?

like image 228
ioannis.th Avatar asked Feb 09 '18 08:02

ioannis.th


Video Answer


1 Answers

You can use the SetEnv directive in the site's Apache configuration file to set environment variables for that site, like this:

SetEnv DATABASE_NAME foo

This needs to go inside the <VirtualHost> directive.

Once you have restarted the server this data should be accessible either via the $_ENV superglobal or getenv(). The downside of this approach is that if your application includes anything that isn't executed by Apache, such as a queue worker or console command, it won't have access to the same variables unless you duplicate them in an appropriate place (eg your .bashrc).

Or you can use a library like DotEnv.

like image 74
Matthew Daly Avatar answered Nov 14 '22 23:11

Matthew Daly