Read environment variables in PHP
Published
Updated
getenv
Reading environment variables from PHP.
PHP reads an environment variable with getenv('NAME') or $_SERVER['NAME']. $_ENV stays empty unless variables_order contains E. Frameworks wrap this in their own helpers.
Read one variable
// Returns the value, or false when the variable is not set
$host = getenv('DB_HOST');
// Same value from the superglobal, undefined key when not set
$host = $_SERVER['DB_HOST'] ?? null;
// Empty unless variables_order contains E
$host = $_ENV['DB_HOST'] ?? null;
getenv() works in every PHP setup. Without an argument, it returns all variables as an array.
Why $_ENV is empty
PHP fills $_ENV only when the variables_order setting contains E. The php.ini-production file that ships with PHP sets it to GPCS, so code that reads $_ENV gets nothing. getenv() and $_SERVER don't depend on that setting.
Frameworks and CMS
Frameworks read the variables for you, from the server environment and from a local .env file:
| Software | Helper |
|---|---|
| Laravel | env('DB_HOST') in config/*.php, config('database...') everywhere else |
| Symfony | %env(DB_HOST)% in the service configuration |
| Craft CMS | App::env('DB_HOST') from craft\helpers\App |
| WordPress | getenv('DB_HOST') in wp-config.php |
In Laravel, call env() only in config files. After php artisan config:cache, Laravel no longer loads the .env file, and env() returns null for variables that only exist there.
ENV vars on fortrabbit
Set ENV vars in the dashboard, changes reach the environment within about a minute. The platform adds its own, such as the database credentials, see ENV vars settings. Never print them on a public page: phpinfo shows them all.
Frequently asked #
Why is $_ENV empty in PHP?
PHP fills $_ENV only when the variables_order setting contains the letter E. The recommended production php.ini sets it to GPCS, without E. Use getenv() or $_SERVER instead.
#How do I list all environment variables in PHP?
Call getenv() without an argument. It returns an array of all environment variables. Never print it on a public page, it contains secrets such as the database password.
#