Environment Variables in PHP

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.

<?php

// To set a key/value pair, use putenv. To get a
// value for a key, use getenv. This will return
// false if the key isn't present in the environment.
putenv("FOO=1");
echo "FOO: " . getenv("FOO") . "\n";
echo "BAR: " . (getenv("BAR") ?: "") . "\n";

// Use getenv(null) to list all key/value pairs in the
// environment. This returns an associative array of
// all environment variables. Here we print all the keys.
echo "\n";
foreach (getenv() as $key => $value) {
    echo $key . "\n";
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ php environment-variables.php
FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 php environment-variables.php
FOO: 1
BAR: 2
...

In PHP, you can also access environment variables directly using the $_ENV superglobal array, although this might require changes to your php.ini configuration. The getenv() function is generally more reliable across different PHP configurations.

Remember that changes made to the environment using putenv() only affect the current process and its child processes. They do not modify the system environment permanently.