Hello everyone, It’s candle
This time I’ll show you how to define environment variables for each virtualhost in apache 2.4 and use it in php
For example, when you are developing with wordpress, you don’t want to put password or access key or anything else under the control of git.
So, you can define it on apache and require it with getenv for use.
anything php project
you have already built some kind of virtual host.
Setting for environment variables
There is the apache configuration file in the following directory when you installed apache by brew.
Open this file and make sure that mod_env is enabled.
LoadModule env_module libexec/mod_env.so
You find out this line and comment out it.
Next, This is the sample virtual host.
We will define an environment variable called HELLO_WORD.
<VirtualHost *:8080> ServerName alice.localhost DocumentRoot /Users/candle/apache/alice_blog SetEnv HELLO_WORD 'hello' <Directory "/Users/candle/apache/alice_blog"> AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost>
If you want to use the environment variables to below any directory, use
In above sample, DocumentRoot is /Users/candle/apache/alice_blog, but if you want to use environment variable in under the all of apache directory, you write following.
<Directory "/Users/candle/apache"> SetEnv GOOD_BYE 'bye' </Directory>
Thne GOOD_BYE=’bye’ will be applied to /Users/candle/apache only when you access to alice.localhsot’s virtual host.
Apache configuration is finished.
using environment variables in php
You can be received apache environment variable with “getenv” or “$_SERVER”.
Let’s display it.
You will create a file and try to receive environment variables.
The root directory is “/Users/candle/apache/alice_blog” in the above sample apache configuration.
You create info.php there.
Write this code.
<?php echo "getenv: ".getenv('HELLO_WORD'); echo "<br />"; echo "SERVER: ".$_SERVER['HELLO_WORD']; echo "<br />"; echo "ENV: ".$_ENV['HELLO_WORD']; ?>
Save it and access.
How is it? It probaly gets the environment variable by getenv and $_SERVER.
If you define environment variables for each virtual host, it is useful because you can change the value depending on the site that accesses even the same environment variable name.