process.env.dev

Environment Variables in PHP

getenv() and $_ENV superglobal

Reading Environment Variables

PHP provides multiple ways to read environment variables: the getenv() function, the$_ENV superglobal, and the $_SERVER superglobal:

text
$dbUrl = getenv('DATABASE_URL');
$port = getenv('PORT') ?: '3000';

// $_ENV is available if variables_order includes 'E' in php.ini
$apiKey = $_ENV['API_KEY'] ?? null;

Setting Environment Variables

text
putenv('MY_VAR=value');

Popular Libraries

vlucas/phpdotenv is the standard .env loader for PHP. Laravel uses it by default. Symfony uses its own Dotenv component.

Common Gotchas

  • $_ENV may be empty if variables_order in php.ini does not include E.
  • getenv() is not thread-safe in PHP-FPM with ZTS. Use $_SERVER instead in those contexts.
  • In Laravel, always use env() helper in config files, then access config values elsewhere with config().