FastSitePHP\Environment\DotEnv

Loads environment variables from a [.env] file into [getenv()] and [$_ENV].

This class is a port of the widely used node [dotenv] package so the following syntax is supported:

  - Empty lines are skipped
  - Lines beginning with # are treated as comments
  - Empty values become empty strings ([EMPTY=] becomes {EMPTY: ''})
  - Whitespace is trimmed for unquoted values ([FOO= some value ] becomes {FOO: 'some value'})
  - Single and double quoted values are escaped ([SINGLE_QUOTE='quoted'] becomes {SINGLE_QUOTE: "quoted"})
  - Double quoted values expand new lines (example: [MULTILINE="new\nline"])

This class is minimal like the node pacakage and does not support nested variables, inline shell execution, or advanced validation. If you prefer to use those features then PHP packages [vlucas/phpdotenv] or [symfony/dotenv] are recommended.

Because FastSitePHP's DotEnv Class is minimal and has fast performance it can be used for production sites, however it’s a good idea to load it from middleware or controller logic on needed routes rather than loading it for every route.

Source Code

GitHub

Example Code

Use a [.env] File

// Loads environment variables from a [.env] file into [getenv()] and [$_ENV].
// FastSitePHP's DotEnv is a port of the Node package [dotenv] so the same
// syntax used by node projects is supported.
$vars = \FastSitePHP\Environment\DotEnv::load($dir);

// Use variables from the file after reading it. Variables are only set
// from the file if they do not already exist.
$value = getenv('DB_CONNECTION');
$value = $_ENV['DB_CONNECTION'];

// Load a file using [.env] file format. The full path of the file is
// specified so it can be named anything.
$vars = \FastSitePHP\Environment\DotEnv::loadFile($file_path);

// Optionally require keys to exist in the file.
$required_vars = ['DB_ORACLE', 'DB_SQL_SERVER'];
$vars = \FastSitePHP\Environment\DotEnv::load($dir, $required_vars);

Methods

load($dir_path, array $required_vars = array())

Static Function

Load a [.env] file from a directory. The directory and file must exist or an exception will be thrown.

An optional array [$required_vars] can be passed and if any key from the array do not exist in the file an exception will be thrown. The actual values are not validated by this class.

Returns an array of all variables read from the file.

Returns: array

loadFile($file_path, array $required_vars = array())

Static Function

Load a file using [.env] file format. The full path of the file is specified so it can be named anything.

Returns: array