Environment variables
suggest changeEvery process gets a set of environment variables: NAME=value string pairs that it inherits from its parent. The shell, systemd, Docker, Kubernetes, CI systems and PHP-FPM all use them to pass settings to a program.
For a PHP application, environment variables are the usual place for settings that change between deployments: database URLs, API keys, the APP_ENV name, debug flags. The code stays the same everywhere and only the environment changes. This is one of the rules of the twelve-factor app.
This article covers reading and setting variables, the difference between getenv(), $_ENV and $_SERVER, turning strings into typed config, .env files, and how web servers pass variables to PHP. All examples were run with PHP 8.5.
For a list of all superglobals see PHP superglobals.
Reading a variable
There are three ways to read a variable:
getenv('NAME')asks the process environment (and the server API, see below) at the moment you call it$_ENV['NAME']is an array filled in when the script starts$_SERVER['NAME']is also an array filled in at startup; in the CLI it contains the environment too
<?php
// getenv() reads one variable from the process environment
var_dump(getenv('APP_ENV'));
var_dump(getenv('DB_PORT'));
var_dump(getenv('NOT_SET'));
// $_ENV and $_SERVER are arrays filled in when the script starts
var_dump($_ENV['APP_ENV'] ?? null);
var_dump($_SERVER['APP_ENV'] ?? null);
Run it with a couple of variables set for this one command:
$ APP_ENV=production DB_PORT=5432 php read.php
Output:
string(10) "production"
string(4) "5432"
bool(false)
string(10) "production"
string(10) "production"
Two things to note:
- the values are always strings, even
5432. Converting them is up to you. getenv()returnsfalsefor a variable that isn't set, notnull.
Why $_ENV is often empty
Whether $_ENV is filled depends on the variables_order ini setting. The built-in default is EGPCS, where E means "environment". But the php.ini-production and php.ini-development files that ship with PHP, and that most distributions and Docker images use, set it to GPCS. Then $_ENV is empty:
$ APP_ENV=production DB_PORT=5432 php -d variables_order=GPCS read.php
Output:
string(10) "production"
string(4) "5432"
bool(false)
NULL
string(10) "production"
getenv() doesn't depend on variables_order, which makes it the most reliable way to read the real environment. Check your setting with php -i | grep variables_order or ini_get('variables_order').
Getting all variables
Call getenv() with no arguments to get every variable as an array:
<?php
$env = getenv(); // no argument: all variables as an array
echo count($env) > 0 ? "got " . gettype($env) . "\n" : "empty\n";
$app = array_filter(
$env,
fn(string $name) => str_starts_with($name, 'APP_'),
ARRAY_FILTER_USE_KEY,
);
ksort($app);
print_r($app);
$ APP_ENV=dev APP_DEBUG=1 APP_NAME=shop php all.php
Output:
got array
Array
(
[APP_DEBUG] => 1
[APP_ENV] => dev
[APP_NAME] => shop
)
Case sensitivity
On Linux and macOS variable names are case-sensitive: APP_ENV and app_env are different variables. On Windows they are not, so getenv('app_env') finds APP_ENV. The keys of $_ENV and $_SERVER are case-sensitive on every OS. Use upper case names everywhere and you won't hit the difference.
Default values
Because a missing variable is false, the ?: operator is a short way to provide a default. Note that ?? does nothing useful with getenv() because it only checks for null. It does work on the arrays:
<?php
// ?: treats both "not set" (false) and "" as missing
$host = getenv('DB_HOST') ?: 'localhost';
// ?? only works on arrays; getenv() never returns null
$port = $_SERVER['DB_PORT'] ?? '5432';
// Explicit check when an empty value is meaningful
$prefix = getenv('CACHE_PREFIX');
if ($prefix === false) {
$prefix = 'app_';
}
echo "host=$host port=$port prefix='$prefix'\n";
$ php defaults.php
$ DB_HOST= CACHE_PREFIX= php defaults.php
$ DB_HOST=db.internal DB_PORT=6432 php defaults.php
Output:
host=localhost port=5432 prefix='app_'
host=localhost port=5432 prefix=''
host=db.internal port=6432 prefix='app_'
Be careful with ?:: the string "0" is falsy in PHP, so getenv('WORKERS') ?: '4' turns WORKERS=0 into 4. When 0 is a valid value, compare with false and '' explicitly, as in the helpers below.
Setting variables with putenv()
putenv('NAME=value') changes the environment of the current process. The change is visible to getenv() and to every child process you start afterwards. It does not update $_ENV or $_SERVER, which were filled in at startup:
<?php
putenv('GREETING=hello');
var_dump(getenv('GREETING'));
var_dump($_ENV['GREETING'] ?? null); // not updated
var_dump($_SERVER['GREETING'] ?? null); // not updated
// Child processes inherit the changed environment
echo shell_exec('php -r "echo getenv(\'GREETING\'), PHP_EOL;"');
// "NAME" without "=" removes the variable
putenv('GREETING');
var_dump(getenv('GREETING'));
Output:
string(5) "hello"
NULL
NULL
hello
bool(false)
The opposite is also true: writing to $_ENV is just an array assignment. It doesn't change the environment:
<?php
$_ENV['FEATURE_X'] = 'on'; // just an array write
var_dump(getenv('FEATURE_X'));
echo shell_exec('php -r "var_dump(getenv(\'FEATURE_X\'));"');
Output:
bool(false)
bool(false)
A change made with putenv() lasts until the end of the request (with PHP-FPM and Apache, PHP restores the original environment after each request). It never affects the parent shell.
Warning: the C function behind putenv() and getenv() is not thread-safe. In a threaded setup (ZTS PHP under Apache's worker MPM, FrankenPHP) one request's putenv() can be seen by another request running at the same time. Treat the environment as read-only configuration and don't use putenv() to pass data around.
Passing an environment to a child process
Commands started with exec(), shell_exec(), system() and proc_open() inherit the PHP process environment. With proc_open() you can pass a custom one as the 5th argument. That array replaces the whole environment, so merge it with getenv() when you only want to add or remove a few variables:
<?php
// child.php
echo 'APP_ENV=', getenv('APP_ENV') ?: '(unset)', "\n";
echo 'SECRET=', getenv('SECRET') ?: '(unset)', "\n";
<?php
function run(array $cmd, ?array $env): string
{
$proc = proc_open($cmd, [1 => ['pipe', 'w']], $pipes, null, $env);
$out = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($proc);
return $out;
}
$cmd = [PHP_BINARY, __DIR__ . '/child.php'];
echo "-- inherit (env = null)\n";
echo run($cmd, null);
echo "-- parent env plus overrides, SECRET removed\n";
$env = ['APP_ENV' => 'test'] + getenv();
unset($env['SECRET']);
echo run($cmd, $env);
$ APP_ENV=production SECRET=s3cr3t php proc.php
Output:
-- inherit (env = null)
APP_ENV=production
SECRET=s3cr3t
-- parent env plus overrides, SECRET removed
APP_ENV=test
SECRET=(unset)
Passing the command as an array (PHP 7.4+) runs it without a shell, so you don't have to escape arguments. Removing secrets before running a third-party tool is a good habit: a child process can read everything in its environment. For more on proc_open() see Spawning non-blocking processes with proc_open.
Converting values to the right type
Every value is a string, so APP_DEBUG=false is the non-empty string "false", which is true in a boolean context. Convert explicitly. filter_var() handles the common spellings of booleans and validates integers (see Filters and filter functions):
<?php
function envBool(string $name, bool $default = false): bool
{
$v = getenv($name);
if ($v === false || $v === '') {
return $default;
}
$b = filter_var($v, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE);
if ($b === null) {
throw new UnexpectedValueException("$name must be a boolean, got '$v'");
}
return $b;
}
function envInt(string $name, int $default): int
{
$v = getenv($name);
if ($v === false || $v === '') {
return $default;
}
$i = filter_var($v, FILTER_VALIDATE_INT);
if ($i === false) {
throw new UnexpectedValueException("$name must be an integer, got '$v'");
}
return $i;
}
function envList(string $name, array $default = []): array
{
$v = getenv($name);
if ($v === false || trim($v) === '') {
return $default;
}
return array_values(array_filter(array_map('trim', explode(',', $v)), 'strlen'));
}
foreach (['true', 'false', '1', '0', 'yes', 'off', 'maybe'] as $raw) {
putenv("APP_DEBUG=$raw");
try {
$result = var_export(envBool('APP_DEBUG'), true);
} catch (UnexpectedValueException $e) {
$result = $e->getMessage();
}
echo str_pad($raw, 6), ' => ', $result, "\n";
}
putenv('WORKERS=8');
var_dump(envInt('WORKERS', 4));
var_dump(envInt('TIMEOUT', 30));
putenv('ALLOWED_HOSTS= example.com, api.example.com ,,');
print_r(envList('ALLOWED_HOSTS'));
putenv('WORKERS=8x');
try {
envInt('WORKERS', 4);
} catch (UnexpectedValueException $e) {
echo $e->getMessage(), "\n";
}
Output:
true => true
false => false
1 => true
0 => false
yes => true
off => false
maybe => APP_DEBUG must be a boolean, got 'maybe'
int(8)
int(30)
Array
(
[0] => example.com
[1] => api.example.com
)
WORKERS must be an integer, got '8x'
Throwing on a bad value is better than silently falling back to the default: a typo like APP_DEBUG=ture should stop the deploy, not quietly run with a setting you didn't ask for. (int) '8x' would give 8 with no warning, which is why the example uses FILTER_VALIDATE_INT.
A typed configuration object
Reading getenv() all over the code base makes it hard to see which variables an application needs. A better pattern: read the environment once, at startup, into a typed read-only object, and pass that object around. Collect all errors so that a misconfigured deploy reports every problem at once:
<?php
final class ConfigException extends RuntimeException {}
final readonly class Config
{
private function __construct(
public string $appEnv,
public bool $debug,
public string $databaseUrl,
public int $workers,
) {}
public static function fromEnv(): self
{
$errors = [];
// Not "?:" - that would turn WORKERS=0 into the default
$get = static function (string $name, ?string $default = null) use (&$errors): string {
$v = getenv($name);
if ($v !== false && $v !== '') {
return $v;
}
if ($default === null) {
$errors[] = "$name is required";
return '';
}
return $default;
};
$appEnv = $get('APP_ENV', 'production');
if (!in_array($appEnv, ['production', 'staging', 'dev', 'test'], true)) {
$errors[] = "APP_ENV has invalid value '$appEnv'";
}
$debug = filter_var($get('APP_DEBUG', 'false'), FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE);
if ($debug === null) {
$errors[] = 'APP_DEBUG must be true or false';
}
$workers = filter_var($get('WORKERS', '4'), FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 64],
]);
if ($workers === false) {
$errors[] = 'WORKERS must be an integer between 1 and 64';
}
$databaseUrl = $get('DATABASE_URL');
if ($errors) {
throw new ConfigException("Invalid configuration:\n - " . implode("\n - ", $errors));
}
return new self($appEnv, $debug, $databaseUrl, $workers);
}
}
try {
$config = Config::fromEnv();
var_dump($config);
} catch (ConfigException $e) {
fwrite(STDERR, $e->getMessage() . "\n");
exit(1);
}
With a valid environment:
$ APP_ENV=dev APP_DEBUG=yes DATABASE_URL=pgsql://localhost/shop php config.php
object(Config)#2 (4) {
["appEnv"]=>
string(3) "dev"
["debug"]=>
bool(true)
["databaseUrl"]=>
string(22) "pgsql://localhost/shop"
["workers"]=>
int(4)
}
With a broken one, the script exits with code 1 and lists every problem:
$ APP_ENV=prod APP_DEBUG=perhaps WORKERS=0 php config.php
Invalid configuration:
- APP_ENV has invalid value 'prod'
- APP_DEBUG must be true or false
- WORKERS must be an integer between 1 and 64
- DATABASE_URL is required
The rest of the application uses $config->workers and gets an int. Tests can build a Config without touching the environment at all if you add a second, public constructor.
.env files
Setting a dozen variables by hand for local development gets old fast. The common solution is a .env file in the project root, read at startup. Keep it out of version control (add .env to .gitignore) and commit a .env.example with dummy values instead.
# Local development settings - do not commit
APP_ENV=dev
APP_DEBUG=true
DATABASE_URL="pgsql://app:secret@localhost:5432/shop"
MAIL_FROM='Shop <noreply@example.com>'
export WORKERS=2
A minimal loader
The format is simple enough to parse yourself for small projects. The important rule: a variable that is already set in the real environment wins over the file, so production settings can't be overridden by a stray .env:
<?php
function loadDotEnv(string $path): void
{
if (!is_readable($path)) {
return;
}
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $n => $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#') {
continue;
}
if (str_starts_with($line, 'export ')) {
$line = substr($line, 7);
}
if (!preg_match('/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/', $line, $m)) {
throw new RuntimeException("$path:" . ($n + 1) . ": invalid line");
}
[, $name, $value] = $m;
// Strip matching surrounding quotes
if (preg_match('/^(["\'])(.*)\1$/', $value, $q)) {
$value = $q[2];
}
// Real environment wins over the file
if (getenv($name) !== false) {
continue;
}
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
loadDotEnv(__DIR__ . '/.env');
foreach (['APP_ENV', 'APP_DEBUG', 'DATABASE_URL', 'MAIL_FROM', 'WORKERS'] as $name) {
printf("%-12s = %s\n", $name, getenv($name));
}
$ php loadenv.php
Output:
APP_ENV = dev
APP_DEBUG = true
DATABASE_URL = pgsql://app:secret@localhost:5432/shop
MAIL_FROM = Shop <noreply@example.com>
WORKERS = 2
With APP_ENV=staging php loadenv.php the first line becomes APP_ENV = staging, because the real environment wins.
This loader doesn't handle escapes inside double quotes, multi-line values, inline # comments or ${VAR} references. For those, use a library.
vlucas/phpdotenv
vlucas/phpdotenv is the most widely used .env loader; Laravel is built on it. Install it with Composer:
$ composer require vlucas/phpdotenv
It supports ${VAR} references and has a small validation API:
APP_ENV=dev
APP_DEBUG=true
DB_HOST=localhost
DB_NAME=shop
DATABASE_URL="pgsql://${DB_HOST}/${DB_NAME}"
WORKERS=2
<?php
require __DIR__ . '/../vendor/autoload.php';
use Dotenv\Dotenv;
use Dotenv\Exception\ValidationException;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
try {
$dotenv->required(['APP_ENV', 'DATABASE_URL'])->notEmpty();
$dotenv->required('APP_ENV')->allowedValues(['production', 'staging', 'dev', 'test']);
$dotenv->required('APP_DEBUG')->isBoolean();
$dotenv->ifPresent('WORKERS')->isInteger();
} catch (ValidationException $e) {
fwrite(STDERR, $e->getMessage() . "\n");
exit(1);
}
echo $_ENV['DATABASE_URL'], "\n";
echo $_SERVER['APP_ENV'], "\n";
var_dump(getenv('APP_ENV'));
$ php app.php
pgsql://localhost/shop
dev
bool(false)
$ APP_ENV=prod php app.php
One or more environment variables failed assertions: APP_ENV is not one of [production, staging, dev, test].
$ APP_ENV=test WORKERS=many php app.php
One or more environment variables failed assertions: WORKERS is not an integer.
Things to know about phpdotenv 5:
createImmutable()never overwrites a variable that is already set. That's whyAPP_ENV=prodfrom the shell won the second run.createMutable()lets the file win.createImmutable()writes only to$_ENVand$_SERVER, not togetenv(), becauseputenv()isn't thread-safe. That's thebool(false)above. If old code readsgetenv(), usecreateUnsafeImmutable().load()throwsInvalidPathExceptionwhen the file is missing.safeLoad()doesn't, which is what you want when production gets its settings from the real environment and has no.envfile.
<?php
require __DIR__ . '/../vendor/autoload.php';
Dotenv\Dotenv::createUnsafeImmutable(__DIR__)->load();
var_dump(getenv('DB_NAME'));
// safeLoad() doesn't throw when the file is missing (e.g. in production)
$vars = Dotenv\Dotenv::createImmutable(__DIR__ . '/nowhere')->safeLoad();
var_dump($vars);
try {
Dotenv\Dotenv::createImmutable(__DIR__ . '/nowhere')->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
echo get_class($e), "\n";
}
Output:
string(4) "shop"
array(0) {
}
Dotenv\Exception\InvalidPathException
Symfony has its own loader, symfony/dotenv, which also supports .env.local and per-environment files such as .env.test.
Parsing .env on every request costs a little time. Frameworks cache the parsed config in production (php artisan config:cache in Laravel, composer dump-env prod in Symfony), and some skip the .env file entirely in production.
Environment variables in php.ini
ini files can read environment variables with ${NAME}. Since PHP 8.3 you can also give a fallback with ${NAME:-default}. This lets one php.ini serve several environments, which is handy in Docker images:
memory_limit = ${PHP_MEMORY_LIMIT}
date.timezone = "${TZ_NAME}"
error_reporting = ${PHP_ERR:-E_ALL}
$ PHP_MEMORY_LIMIT=256M TZ_NAME=Europe/Warsaw php -n -c custom.ini \
-r 'echo ini_get("memory_limit"), " ", date_default_timezone_get(), " ", ini_get("error_reporting"), "\n";'
256M Europe/Warsaw 30719
30719 is the value of E_ALL in PHP 8.4+; the fallback was used because PHP_ERR wasn't set.
Web servers
In the CLI, PHP sees the environment of the shell that started it. Under a web server it's more complicated, because there are two sources of variables: the environment of the server process, and variables the server sets per request.
Built-in server
php -S passes its own environment through, so you can test with:
$ APP_ENV=staging php -S 127.0.0.1:8123 -t web
<?php
header('Content-Type: text/plain');
echo 'getenv: ', var_export(getenv('APP_ENV'), true), "\n";
echo '$_ENV: ', var_export($_ENV['APP_ENV'] ?? null, true), "\n";
echo '$_SERVER:', var_export($_SERVER['APP_ENV'] ?? null, true), "\n";
Requesting the page with variables_order=GPCS prints:
getenv: 'staging'
$_ENV: NULL
$_SERVER:NULL
Unlike the CLI, the built-in server doesn't copy the environment into $_SERVER. Again, getenv() is the one that works. See Running built-in web server.
PHP-FPM
By default PHP-FPM starts workers with clear_env = yes, which wipes the environment. A variable set in the shell or the Docker container that started FPM won't reach your code. Either list the variables you want in the pool config, or turn clearing off:
; /etc/php/8.5/fpm/pool.d/www.conf
[www]
; pass selected variables from the FPM master's environment
env[APP_ENV] = $APP_ENV
env[DATABASE_URL] = $DATABASE_URL
; or pass everything (the official Docker php-fpm image does this)
; clear_env = no
The web server in front of FPM can also send per-request values as FastCGI parameters. In nginx:
location ~ \.php$ {
include fastcgi_params;
fastcgi_param APP_ENV production;
fastcgi_pass unix:/run/php/php8.5-fpm.sock;
}
These arrive in $_SERVER, and getenv('APP_ENV') finds them too, because getenv() asks the server API first. Pass true as the second argument, getenv('APP_ENV', true), to read only the real process environment.
Apache
With mod_php or FPM behind Apache, SetEnv sets a per-request variable that shows up in $_SERVER and getenv():
<VirtualHost *:80>
SetEnv APP_ENV production
# or pass through a variable from Apache's own environment
PassEnv DATABASE_URL
</VirtualHost>
Testing code that reads the environment
Code that reads the environment at startup into a Config object is easy to test: build the object directly. When you must test code that calls getenv(), change the variable and restore it afterwards, or one test will leak into the next:
<?php
/**
* Run $fn with some variables set (string) or removed (null),
* then restore the previous values even if $fn throws.
*/
function withEnv(array $vars, callable $fn): mixed
{
$saved = [];
foreach ($vars as $name => $value) {
$saved[$name] = getenv($name);
putenv($value === null ? $name : "$name=$value");
}
try {
return $fn();
} finally {
foreach ($saved as $name => $old) {
putenv($old === false ? $name : "$name=$old");
}
}
}
function cacheTtl(): int
{
return (int) (getenv('CACHE_TTL') ?: 60);
}
putenv('CACHE_TTL=300');
echo cacheTtl(), "\n";
echo withEnv(['CACHE_TTL' => '5'], cacheTtl(...)), "\n";
echo withEnv(['CACHE_TTL' => null], cacheTtl(...)), "\n";
echo cacheTtl(), "\n";
Output:
300
5
60
300
PHPUnit can set variables for the whole test run in phpunit.xml. force="true" overrides a value that is already set:
<phpunit>
<php>
<env name="APP_ENV" value="test" force="true"/>
<env name="DATABASE_URL" value="sqlite::memory:"/>
</php>
</phpunit>
See also Testing in CI.
Keeping secrets secret
Environment variables are the standard place for secrets, but they leak easily:
phpinfo()prints the whole environment and$_SERVER. Never leave aphpinfo()page on a public server (see phpinfo).- Error pages and debug toolbars that dump
$_SERVERor$_ENVshow your database password to whoever triggers an error. Turndisplay_errorsoff in production. - Child processes inherit everything. Remove secrets from the environment you pass to tools that don't need them, as in the
proc_open()example. - Don't commit
.env. Commit.env.example. - On a shared host, other users may be able to read a process's environment (for example through
/proc/<pid>/environon Linux if permissions are loose). For high-value secrets, consider mounting them as files (Docker and Kubernetes secrets) and reading them withfile_get_contents(). A common convention is aDATABASE_PASSWORD_FILEvariable that holds the path to the file.
Summary
- Read the real environment with
getenv('NAME'); it returns a string orfalse. $_ENVis empty unlessvariables_ordercontainsE, which the shippedphp.inifiles don't.putenv()changesgetenv()and child processes, not$_ENV/$_SERVER. It isn't thread-safe.- Values are strings: convert with
filter_var()and fail loudly on bad values. - Read the environment once at startup into a typed, read-only config object.
- Use a
.envfile for local development only, and let the real environment win. - With PHP-FPM, remember
clear_env; per-request server variables arrive in$_SERVER. - See Docker deployment for passing variables to a containerized app.