Search by

sugiphp / dotenv

tzappa

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

Package info

github.com/SugiPHP/DotEnv

pkg:composer/sugiphp/dotenv

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main 2026-09-18 13:10 UTC

This package is auto-updated.

Last update: 2026-09-18 13:12:07 UTC


README

A minimal PHP library for loading environment variables from a .env file. Values are set into $_ENV and made available through PHP's getenv(), so the rest of your application can read configuration without caring where it came from.

Requirements

  • PHP >= 8.3

Installation

composer require sugiphp/dotenv

Usage

Create a .env file in your project (commonly in the project root, next to composer.json):

DB_HOST=localhost
DB_NAME=my_database
DB_USER=root
DB_PASS="a secret with spaces"

Load it as early as possible in your bootstrap script:

<?php

use SugiPHP\DotEnv\DotEnv;

require __DIR__ . '/vendor/autoload.php';

(new DotEnv(__DIR__))->load();

echo getenv('DB_HOST');   // "localhost"
echo $_ENV['DB_NAME'];    // "my_database"

DotEnv throws a RuntimeException if the file cannot be found or read, so wrap load() in a try/catch if a missing .env file is not fatal for your application.

If putenv() and/or getenv() are disabled (e.g. via disable_functions on hardened hosting), load() degrades gracefully instead of failing: it still populates $_ENV, but skips whichever of the two functions is unavailable. In that case:

  • If putenv() is disabled, values are only available via $_ENV, not getenv().
  • If getenv() is disabled, load() can no longer detect real environment variables set outside of PHP's $_ENV, so the "don't overwrite existing variables" guarantee only covers $_ENV in that case.

Custom file name

By default the library looks for .env in the given directory. Pass a second argument to use a different file, e.g. to load environment-specific configuration:

(new DotEnv(__DIR__, '.env.testing'))->load();

.env file format

  • Each variable is defined on its own line as KEY=value.
  • Blank lines are ignored.
  • Lines starting with # are treated as comments and ignored.
  • Leading/trailing whitespace around both the key and the value is trimmed.
  • Values may be wrapped in single or double quotes; the surrounding quotes are stripped. Unmatched quotes are kept as part of the value.
  • Only the first = on a line is treated as the separator, so values containing = (e.g. connection strings) are preserved in full.
  • Variables that already exist in the environment (checked via both $_ENV and getenv()) are not overwritten, so real environment variables always take precedence over the .env file.
  • If the same key is defined more than once within the same .env file, the last occurrence wins.

Example:

# Database
DB_DSN=pgsql:dbname=app;host=localhost
DB_PASS='p@ss=word'

# Feature flags
FEATURE_X_ENABLED=true

Testing

composer test