- Set Environment Variable
- Set Environment Variable Permanently
- Set Environment Variable In htaccess
- Get Environment Variable
- Including Configuration File
Quite often application are developed, tested and deployed on different servers, and connect to different databases.
This facilitates the need to change config files for each deployment. However, with the use of environment varialbes, a single config file can be crafted for each environement and PHP is capable of detecting which enviroment it is in.
In this tutorial we are using linux (ubuntu), so for windows users click my computer -> properties -> advanced system settings,
Setting an enviroment is a simple command line instruction. In this example, an environment variable will be set for an application named MYAPP.
The environment variable is now set for the development (dev) environment.
Of course, the above command will only set the environment variable temporarily. To set the environment variable permently a little more is required.
In linux, the files /etc/profile, ~/.bash_profile, ~/.bash_login, ~/.profile in that order. So to set the environment variable permantly, the command can be placed in /etc/profile. Depending on the linux distro, the file /etc/environment can also be used.
To test and see the environment variable use this command
sudo service apache2 restart
To set the environment in the htaccess file use this syntax
With this set, the environment variable is now set and can be retrieved in the same way with getenv().
Getting an environment variable in PHP is made easy with the use of the getenv() function. So you get the newly created MYAPP_ENV value we use this..
echo getenv ( 'RHINO_ENV' );
This should be academic now that the invironment variable can be captured with the getenv() function.
// get the environment variable
$env = getenv( 'MYAPP_ENV' );
// choose config based on environment
switch( $env )
default: throw new exception( "Invalid Environment $env" );
Now the application can have three seperate config files and nasty accidents are prevented when a config file is not editted to suit the environment.