Load environment variables into $_ENV and $_SERVER

The dotenv composer package is a great way to parse a complex .env file.

Sometimes you just need a way to parse a simple .env file, and keep configuration settings out of version control by adding .env to the .gitignore file.

parse_ini_file parses a simple .ini file into an array. The following function performs a similar parsing, but will insert the keys and values into $_ENV and $_SERVER.

.env

DATABASE_DNS=sqlite:dbname=test
DATABASE_USER=root
DATABASE_PASSWORD=password

parse_env_file

function parse_env_file($filename) {
    $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') !== 0) {
            list($key, $value) = array_map('trim', explode('=', $line, 2));
            if (!array_key_exists($key, $_ENV) && !array_key_exists($key, $_SERVER)) {
                putenv(sprintf('%s=%s', $key, $value));
                $_ENV[$key] = $_SERVER[$key] = $value;
            }
        }
    }
}

Usage

parse_env_file('path/to/.env');
echo getenv('DATABASE_DNS'); //-> "sqlite:dbname=test"
echo $_ENV['DATABASE_DNS']; //-> "sqlite:dbname=test"
echo $_SERVER['DATABASE_DNS']; //-> "sqlite:dbname=test"