Access PHP Environment Variables with getenv and $_ENV

Managing configuration settings securely is crucial in web development. This article explains how to access environment variables in PHP using the built-in getenv() function and the $_ENV superglobal, highlighting their differences, use cases, and how to configure PHP to ensure they work correctly.

Using the getenv() Function

The getenv() function is a built-in PHP function used to retrieve the value of an environment variable. It queries the system or web server environment directly.

To use it, pass the name of the variable as a string argument:

// Retrieve an environment variable
$databaseUrl = getenv('DATABASE_URL');

if ($databaseUrl !== false) {
    echo "Database URL is: " . $databaseUrl;
} else {
    echo "Environment variable not found.";
}

If the environment variable does not exist, getenv() returns false.

Using the $_ENV Superglobal

$_ENV is an associative array that PHP automatically populates with environment variables. It allows you to access variables as array keys.

// Retrieve an environment variable using $_ENV
$apiKey = $_ENV['API_KEY'] ?? 'default_key';

echo "API Key is: " . $apiKey;

Using the null coalescing operator (??) is recommended to prevent “Undefined array key” warnings in case the variable is not set.

Why $_ENV Might Be Empty: The variables_order Setting

If $_ENV is empty or returns null despite the variables being set, it is usually due to the variables_order directive in your php.ini file. By default, many production PHP installations disable the loading of environment variables into the $_ENV superglobal for performance reasons.

To fix this: 1. Open your php.ini file. 2. Locate the variables_order directive. It often looks like this: variables_order = "GPCS". 3. Add E (which stands for Environment) to the string: variables_order = "EGPCS". 4. Restart your web server (Apache, Nginx, or PHP-FPM).

Key Differences: getenv() vs $_ENV

While both methods retrieve environment variables, they behave differently: