Skip to main content

How to Read an Environment Variable in PHP

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Settings that change between computers, such as a database address or an API key, belong in environment variables. PHP reads one with getenv('NAME'), which returns the value as a string, or false when the variable isn't set.

Syntax​

Syntax
$<value> = getenv('<NAME>');
PartWhat it does
getenv('<NAME>')Reads one environment variable.
ResultThe value as a string, or false when the variable doesn't exist.

The PHP manual for getenv: it "Returns the value of the environment variable name, or false if the environment variable name does not exist."

The Example​

The example shows what getenv('GREETING') returns, with var_dump so the type is visible too, first with the variable set and then without it.

Prerequisites​

  • PHP for the command line. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, which stores getenv('GREETING') in $greeting and var_dumps it.

main.php
<?php

$greeting = getenv('GREETING');

var_dump($greeting);

Step 2: Set the Variable and Run It​

Set GREETING to Hello and run the script. Then remove the variable and run it again:

Terminal
export GREETING=Hello
php main.php
unset GREETING
php main.php

A zsh terminal where export GREETING=Hello and php main.php print string(5) "Hello", and after unset GREETING the same command prints bool(false).

Output
string(5) "Hello"
bool(false)

With the variable set, getenv returned the string "Hello". Without it, it returned false, not an empty string, so test for false with ===.

What About $_ENV?​

$_ENV is only filled in when the variables_order setting includes E. This PHP's php.ini sets variables_order to GPCS, so $_ENV had 0 entries and $_ENV['GREETING'] wasn't there, while getenv('GREETING') returned Hello. getenv doesn't depend on that setting.

Common Mistakes​

MistakeWhat happensDo this instead
Testing with if ($value == '')It's also true for false, hiding the differenceCompare with === false
Reading $_ENV['NAME']Empty when variables_order has no EUse getenv('NAME')
Setting the variable in one terminal and running PHP in anotherfalse: each terminal has its own variablesSet it in the terminal that runs PHP

Troubleshooting​

SymptomLikely causeFix
getenv returns falseThe variable isn't set in this terminal, or the name differsSet it as in Step 2
$_ENV is emptyvariables_order is GPCSUse getenv, or add E to variables_order

FAQ​

Are variable names case-sensitive?​

On macOS and Linux, yes. Windows treats GREETING and greeting as the same variable.

What about web servers?​

Under a web server, which variables PHP sees depends on the server's configuration; getenv still reads whatever reached the PHP process.

Conclusion​

getenv('NAME') returns a variable's value as a string, or false when it isn't set. Compare the result with === false, and prefer getenv to $_ENV, which may be empty.

Additional Resources​