dotenv

Configuration from .env files and the environment.

v1.0.0Tooling & CLIbundledimport "dotenv";
Overview Installation Documentation Examples

Overview

Keep configuration out of your code: load .env files into the environment and read values with typed getters. Real environment variables win, so the same program runs locally with a .env file and in production with real variables.

bundled — works offline .env files env_int, env_bool ${VAR} expansion

Quick start

# .env
PORT=8080
DEBUG=true
DATABASE_URL=sqlite:app.db
import "dotenv";

env_load();                              // reads ./.env when it exists
$port = env_int("PORT", 3000);
$debug = env_bool("DEBUG", false);
$db = env("DATABASE_URL", "sqlite:dev.db");

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install dotenv

This adds the library to hphp.yaml, installs it into .hphp/packages/dotenv/ and pins the exact version in hphp.lock:

require:
  dotenv: "^1.0"

Use it

import "dotenv";

dotenv is bundled with the compiler, so import "dotenv"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install dotenv          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install dotenv
Packagedotenv
Version1.0.0 (follows the compiler)
Entry filedotenv.hphp
Sourcepackages/lib/dotenv ↗

Documentation

Functions

FunctionWhat it does
env_load($path = ".env", $override = false)loads a file into the environment; returns how many keys it set (0 when the file is missing). Existing variables are kept unless $override
env($key, $default = "")the value, or the default when unset or empty
env_int($key, $default = 0)the value as an int (default when not numeric)
env_bool($key, $default = false)true/yes/on/1 and false/no/off/0, any case
env_has($key)whether the variable is set and not empty
env_required($key)the value; throws "missing environment variable: KEY" when unset
env_parse($text)parses .env text into a map, without touching the environment

.env syntax

# comments start with #
export APP_NAME=Demo App          # "export " is allowed, spaces inside are kept
PORT=8080
GREETING="Hello\nWorld"           # double quotes: \n and \" escapes, ${VAR} expansion
PATTERN='${NOT_EXPANDED}'         # single quotes: taken literally
URL=http://localhost:${PORT}/api  # expansion also works without quotes

Loaded values go into the process environment with putenv, so getenv() and child processes started with exec() see them too.

Examples

3 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.

01Load configuration from .env

Put settings in a .env file next to the program (and keep it out of git). env_load() reads it; the typed getters return a default when a value is missing. Real environment variables win over the file.

01-load-config.hphp
<?php
import "dotenv";

$loaded = env_load();
echo "read " . $loaded . " settings from .env";

$name = env("APP_NAME", "my app");
$port = env_int("PORT", 8080);
$debug = env_bool("DEBUG", false);

echo "app:   " . $name;
echo "port:  " . $port;
echo "debug: " . ($debug ? "on" : "off");
Try it
printf "APP_NAME=Shop\nPORT=9000\nDEBUG=yes\n" > .env
hphp run 01-load-config.hphp
PORT=7000 hphp run 01-load-config.hphp

02Fail early on missing settings

Settings without a sensible default (an API key, a database URL) should stop the program at start with a clear message, not crash later. env_required() throws when a variable is missing; catching it once gives a friendly error.

02-required-settings.hphp
<?php
import "dotenv";

env_load();

// everything the program cannot run without, checked in one place
function load_settings(): array {
    $settings = [];
    $settings["api_key"] = env_required("API_KEY");
    $settings["database"] = env_required("DATABASE_URL");
    $settings["timeout"] = env_int("TIMEOUT_SECONDS", 30);
    return $settings;
}

try {
    $settings = load_settings();
} catch (string $e) {
    echo "configuration error: " . $e;
    echo "set it in .env or in the environment, then start again";
    exit(1);
}

echo "database: " . $settings["database"];
echo "timeout:  " . $settings["timeout"] . " s";
echo "api key:  " . substr($settings["api_key"], 0, 3) . "...";
Try it
hphp run 02-required-settings.hphp
API_KEY=abc123 DATABASE_URL=sqlite:app.db hphp run 02-required-settings.hphp

03Development, test and production

A common layout: .env holds the defaults for everyone, .env.<mode> the values for one environment, and .env.local personal overrides that are never committed. Later files override earlier ones.

03-environments.hphp
<?php
import "dotenv";

// 1. shared defaults
env_load(".env");

// 2. the environment's own file, chosen by MODE
$mode = env("MODE", "development");
env_load(".env." . $mode, true);

// 3. personal overrides, highest priority
env_load(".env.local", true);

echo "mode:      " . $mode;
echo "log level: " . env("LOG_LEVEL", "warning");

// ${VAR} inside values is expanded when the file is read
$parsed = env_parse("HOST=localhost\nURL=http://\${HOST}:8080/api\n");
echo "expanded:  " . $parsed["URL"];
Try it
printf "MODE=test\nLOG_LEVEL=info\n" > .env
printf "LOG_LEVEL=debug\n" > .env.test
hphp run 03-environments.hphp