vlucas/phpdotenv
vlucas/phpdotenv loads environment variables from a .env file into getenv(), $_ENV, and $_SERVER. Ideal for keeping secrets out of code and managing per-environment configuration in PHP apps via simple, portable dotenv files.
Start by installing the package via Composer:
composer require vlucas/phpdotenv
Then create a .env file in your project root (outside version control) with key-value pairs:
APP_ENV=local
DB_HOST=localhost
DB_PASSWORD=supersecret
Also create a .env.example file (checked into VCS) with placeholders to guide collaborators.
Load env vars early in your app’s lifecycle:
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
Access variables via $_ENV['KEY'], $_SERVER['KEY'], or (with createUnsafeImmutable) getenv('KEY').
DotEnv preconfigured in bootstrap/app.php. Use config() with env() behind the scenes — but avoid calling env() outside config files (it may be cached/undefined in production).load():
$dotenv->required(['APP_KEY', 'DB_HOST'])->notEmpty()->isString();
$dotenv->required('APP_DEBUG')->isBoolean();
.env.local, .env.staging, etc. by passing filename:
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__, $_ENV['APP_ENV_FILE'] ?? '.env');
$dotenv->load();
$repo = Dotenv\Repository\RepositoryBuilder::createWithDefaultAdapters()
->immutable()
->allowList(['APP_', 'DB_'])
->make();
$dotenv = Dotenv\Dotenv::create($repo, __DIR__)->load();
.env.testing or override in tests by calling createMutable() before loading.createImmutable() (default) refuses to overwrite existing env vars (e.g., set via Apache/Nginx). Use createMutable() only if you must override system vars — but be cautious for security.getenv() vs Superglobals: Superglobals ($_ENV, $_SERVER) are populated during load; getenv() reflects current state. For CLI scripts, prefer superglobals (they’re populated reliably).variables_order in php.ini includes E and S (e.g., variables_order = "EGPCS"); otherwise $_ENV/$_SERVER may be empty.# or =. Nested vars (${FOO}) are resolved at parse time..env is for development/local setups. In production, prefer native env vars (set by process manager, container, or cloud platform) — don’t deploy .env files.isInteger() expects an integer string (e.g., "123"), not floats like "12.0". Use isNumeric() for floats/ints..env should be in .gitignore. Never commit secrets. Use .env.example + documentation to guide onboarding.$vars = Dotenv\Dotenv::parse(file_get_contents(__DIR__.'/.env'));
How can I help you explore Laravel packages today?