Environment variables are named values set outside your code, for example by the server, the hosting panel or a Docker file. They are the standard place for settings that differ between your laptop and the live server, and for secrets such as database passwords.
getenv(): the reliable way
<?php
putenv("APP_MODE=development"); // set one for this script, as a demo
echo getenv("APP_MODE") . "\n";
var_dump(getenv("DOES_NOT_EXIST"));
development
bool(false)
getenv() returns the value as a string, or false when the variable is not set.
A default value
<?php
$mode = getenv("APP_MODE") ?: "production";
echo $mode;
production
(In a fresh terminal without APP_MODE, the fallback is used.)
$_ENV is often empty
$_ENV should hold the environment, but it is filled only when variables_order in php.ini contains E. Many default configurations use "GPCS", so $_ENV is empty and getenv() still works. That is why most code uses getenv().
<?php
var_dump(ini_get("variables_order")); // for example string(4) "GPCS"
Where do the values come from?
- The server or hosting control panel.
- Docker or CI settings.
- A
.envfile read by a library (such asvlucas/phpdotenv), which then makes the values available. Never put the.envfile inside the public web folder. - Apache
SetEnvor PHP-FPMenv[...]settings.
Why use them
- Secrets stay out of your code and out of Git.
- The same code runs everywhere. Only the settings change.
- Safer deployment. You change a password without editing a PHP file.
<?php
putenv("DB_HOST=localhost");
putenv("DB_NAME=shop");
$config = [
"host" => getenv("DB_HOST") ?: "127.0.0.1",
"name" => getenv("DB_NAME") ?: "app",
];
echo $config["host"] . "/" . $config["name"];
localhost/shop
Environment Variables in the practical chapter builds this into a small configuration helper.
Never print the environment
phpinfo() and print_r($_ENV) can show passwords and API keys. Never leave them on a live page.