Skip to content

PHP Tutorial Superglobals

$_ENV and getenv()

Lesson 153 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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

index.php
PHP
<?php
putenv("APP_MODE=development");   // set one for this script, as a demo

echo getenv("APP_MODE") . "\n";
var_dump(getenv("DOES_NOT_EXIST"));
Output
OUTPUT
development
bool(false)

getenv() returns the value as a string, or false when the variable is not set.

A default value

index.php
PHP
<?php
$mode = getenv("APP_MODE") ?: "production";

echo $mode;
Output
OUTPUT
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().

index.php
PHP
<?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 .env file read by a library (such as vlucas/phpdotenv), which then makes the values available. Never put the .env file inside the public web folder.
  • Apache SetEnv or PHP-FPM env[...] settings.

Why use them

  1. Secrets stay out of your code and out of Git.
  2. The same code runs everywhere. Only the settings change.
  3. Safer deployment. You change a password without editing a PHP file.
index.php
PHP
<?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"];
Output
OUTPUT
localhost/shop

Environment Variables in the practical chapter builds this into a small configuration helper.

dangerous
Never print the environment
phpinfo() and print_r($_ENV) can show passwords and API keys. Never leave them on a live page.