dotenv & Config

.env configuration with safe defaults and zero secret leakage.

On this page

Why .env

.env files are a local/development convenience for environment variables. In production, prefer real environment variables or secret managers. Never commit real secrets to Git.

Install dotenv

composer require vlucas/phpdotenv

Create a .env File

Keep it out of version control (use .gitignore).

APP_ENV=local
DB_HOST=127.0.0.1
DB_NAME=app
DB_USER=root
DB_PASS=

Load .env in Bootstrap

Load env as early as possible (front controller / bootstrap).

<?php
require __DIR__ . "/../vendor/autoload.php";

$dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->safeLoad();

Read Config Safely

<?php
$env = $_ENV["APP_ENV"] ?? "production";
$dbHost = $_ENV["DB_HOST"] ?? "127.0.0.1";

Production Tip

Use .env only for local/dev. In production, inject environment variables via server/container config. Validate required variables and fail fast if missing.