We're live-coding on Twitch! Join us!
How to Use Environment Variables

How to Use Environment Variables

Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer.

In simple terms, Evironment Variables are variables that are set depending on the computer (server) the software is running on. Have you by chance heard "Add a program to PATH"? It could be PHP or composer — but you've heard something like this, especially when trying to install a software you use. PATH is an example of an Environment Variable.

Testing is an integral part of app development. Some people test their code on a local machine. While others prefer to set up a live test server with the same configuration as their production server. Then they run their tests to see if the app will work fine in a production environment.

When I was first learning to version control my code with git, I was told to never put sensitive data in source code. Sensitive data includes database password, API keys etc. Now that we know not to put sensitive data in source, how then do we tell the application the pass key to use? The answer, you guessed it — Environment Variables.

Setting Environment Variables

Setting environment variables differs on the operating system in question. I will show you how to environment variables in Linux and Windows environment, and finally using PHP.

In Linux

To create an environment variable in Linux, we can just run the following command.

export DB_PASSWORD="25v3(:/9C"s:WHA`"

to view the content of the environment variable, you can do this.


And there, we have our super secure database password set. The problem with this method is that we lose the variable as soon as we close the terminal.

To make it permanent, edit your .bashrc file and add the above command at the bottom of the file.

I prefer writing all environment variables in a separate file and include the file in .bashrc file. To do that, go to root and create a new file, I call mine .bash_exports.

cd ~
touch .bash_exports

Then I use vim editor to include my exports and save the file. To include the file in .bashrc, open the .bashrc file and add this line at the bottom.

if [ -f $HOME/.bash_exports ]; then
    . $HOME/.bash_exports

This checks to see if the file exists; if it does, source/import it.

Enviroment Variables in Windows

Setting environment variables in windows take a more graphical approach. Go to Control Panel\System and Security\System and in the left panel, click on Advanced system settings. A popup dialog appears, click on environment variables.

Environment variable popup dialog

In the popup that appears, there are two sections. The first one holds user variables while the second one holds system variables.

Environment variable picker

Not to confuse you, System Variables and User Variables both make up environment variables on Windows. The difference between them is that System Variables are system-wide, while User Variables are for the current user.

Now click on the new button on the section you decide to save the variable, a dialog pops up asking you to enter a key and a value and hit save. To see if the variable exists, open a command prompt and type


and you should see the value of the variable. On Windows, the % sign before and after the variable name is important.

Setting Environment Variables In PHP

To set an environment variable in PHP, we can use one of two ways. The first is using the $_ENV super global

$_ENV['VARIABLE_NAME'] = 'super sentitive key';

or a more preferable way to set environment variables in PHP would be to use the putenv function.


Getting Environment Variables with PHP

Just like setting environment variables, we can get environment variables using one of two methods. The first is to access the variable from the $_ENV superglobal, while the other requires us to use the more preferable getenv function.

echo $_ENV['PATH'];


echo getenv('PATH');

A Better Way to Handle Environment Variables in PHP

The above method works fine. Most people just add this snippet to their application bootstrap file. This defeats the purpose of "never add sensitive data to version control".

We could come up with a way to use environment variables. We could create a PHP file and exclude that file from version control and then add all our Environment variables in that file. Then we could run a check that ensures the file exist, if not throw an error exception and alert the developer, telling them to create the file. This was what I used for a while until I found DotEnv. It was a much cleaner solution than using the file method above.

What does DotEnv offer

This library offers us the following set of features:

  • We can load variables to the environment.
  • Let's us define the environment variables that are must-use.
  • Provides an env function as a shorthand to $option = getenv('VARIABLE') ? getenv('VARIABLE') : $default;.
  • Nest environment variables.
  • Validation for variables.

Get Started with DotEnv

This library needs you to create a .env file which you can put your environment variables as key-value pairs.

Example .env file looks like this

DB_NAME=database name

The key is the string before the equals sign, while after the equals sign is the value. Notice the value can also be in quotes, it all depends on personal preference.

First before we can use the library, we can download the package from github or install it via composer. Let's install our copy with composer.

composer require --dev phpdotenv

After installing the library, we can then create our index.php file and include composer autoloader.

require __DIR__ . '/vendor/autoload.php';

after autoloading the installed package, we can then tell DotEnv to load the .env file.

$dotenv = new Dotenv\Dotenv(__DIR__);

DotEnv constructor takes the directory of the .env file. Optionally, we can change the name of the environment loader file.

$dotenv = new Dotenv\Dotenv(__DIR__, 'new-config-file-name');

Accessing DotEnv Data

Like we earlier mentioned, we could use the getenv php function to get the value from the environment. But DotEnv provides an env function that we can use. env is shorter than getenv and most importantly, takes in a second parameter that acts as the default value.

// try and find the creator of PHP otherwise return Rasmus Lerdorf
$option = env('PHP_CREATOR', 'Rasmus Lerdorf'); 

Overwriting Existing Environment Variables

Sometimes, albeit very rare, an environment might exist and overwrite the one you set in your .env file. To prevent something like this from happening, we can tell DotEnv to overwrite existing environment variables.

$dotenv = new Dotenv\Dotenv(__DIR__, 'new-config-file-name');

Sample Application

The last project I worked on was WordPress based, here is a look at the wp-config.php file.

Using environment variables in PHP

As you can see, I can add the wp-config file to git without worrying about exposing any sensitive data to the public. I even went as far as to add the database collation to the .env.


By now, I hope you understand environment variables, and why you should use them more often than not in your application.

Like this article? Follow @KayandraJT on Twitter