Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read an environment variable

Short answer

getenv() returns the value, or false if the variable does not exist:

<?php
 
putenv('APP_ENV=production');
 
echo getenv('APP_ENV'), ' ', getenv('MISSING_VARIABLE') ?: 'default';

Output:

production default

A required variable

Without a database password nothing works — better to stop at once with a clear error:

<?php
 
function requireEnv(string $name): string
{
    $value = getenv($name);
 
    if ($value === false || $value === '') {
        throw new RuntimeException("Environment variable $name is not set");
    }
 
    return $value;
}
 
try {
    requireEnv('DB_PASSWORD_FOR_RECIPE');
} catch (RuntimeException $e) {
    echo $e->getMessage();
}

Output:

Environment variable DB_PASSWORD_FOR_RECIPE is not set

Functions used in this recipe

  • getenv — Returns the value of an environment variable.
  • parse_ini_file — Reads a settings file in ini format.
  • define — Creates a constant at run time.

Thanks for reading!

Donate to the site — we work hard for you.