Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

getenv

Returns the value of an environment variable.

Syntax

getenv(?string $name = null, bool $local_only = false): string|array|false

Parameters

ParameterTypeDescription
$name?stringOptional. The variable name; without it all are returned.
$local_onlyboolOptional. Only variables set with `putenv()`.

Return value

string|array|falseThe value, or `false` if the variable does not exist.

Examples

A default value:

<?php
 
putenv('APP_MODE=test');
 
echo getenv('APP_MODE'), "\n";
echo getenv('NO_SUCH_VARIABLE') ?: 'default';

Output:

test
default

Notes

Passwords and keys are kept in environment variables rather than in code. A missing variable gives false, not null, so ?? does not help here — use ?:.

See also

  • parse_ini_file — Reads a settings file in ini format.
  • define — Creates a constant at run time.
  • ini_set — Changes a PHP setting for the duration of the program.

Related recipes

In the tutorial

  • Configuration and environment — Where to keep the settings of a PHP project — a configuration file, environment variables, the .env file, different modes for development and the server.

Thanks for reading!

Donate to the site — we work hard for you.