Skip to main content

Lesson 5 of 8

Environment Configuration - .env, Secrets & Config Hierarchy

Production applications require different configuration from development - database hosts, API keys, debug settings, log levels. The .env file (loaded by phpdotenv) separates configuration from code. Secrets (API keys, DB passwords) must never be in version control. Environment-specific config is the Twelve-Factor App methodology applied to PHP.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Environment Configuration Best Practices

Environment Configuration Best Practices
# ── .env file - development (NOT committed to git) ─────────────
APP_NAME="Blog System"
APP_ENV=development
APP_DEBUG=true
APP_URL=http://localhost:8000

DB_DSN="mysql:host=127.0.0.1;port=3306;dbname=blog_dev;charset=utf8mb4"
DB_USER=root
DB_PASSWORD=

CACHE_DRIVER=array        # no Redis in dev
LOG_CHANNEL=stdout
LOG_LEVEL=debug

MAIL_DRIVER=log           # log emails instead of sending
NOTIFIER_DRIVER=log

# ── .env.production (on server - env variables, not file) ──────
# Best practice: set via server environment, not .env file
# On server: export APP_ENV=production in /etc/environment
# Or use systemd: EnvironmentFile=/var/www/html/blog/shared/.env

APP_ENV=production
APP_DEBUG=false
APP_URL=https://blog.example.com

DB_DSN="mysql:host=localhost;dbname=blog_prod;charset=utf8mb4"
DB_USER=blog_user
DB_PASSWORD=STRONG_RANDOM_PASSWORD_HERE

CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_DB=0

LOG_LEVEL=warning
LOG_CHANNEL=daily

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=SG.xxxxxxxxxx

JWT_SECRET=64_CHAR_RANDOM_SECRET_NEVER_IN_GIT

<?php
declare(strict_types=1);
// composer require vlucas/phpdotenv

// ── Loading .env ──────────────────────────────────────────────
use DotenvDotenv;

$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

// Required variables - throws if missing in production
$dotenv->required(["DB_USER", "DB_PASSWORD", "DB_DSN", "APP_ENV"]);
$dotenv->required("APP_ENV")->allowedValues(["development", "staging", "production"]);

// ── Config class - typed access with defaults ─────────────────
class AppConfig {
    public static function dbDsn(): string { return $_ENV["DB_DSN"] ?? "mysql:host=localhost;dbname=blog;charset=utf8mb4"; }
    public static function isProduction(): bool { return ($_ENV["APP_ENV"] ?? "production") === "production"; }
    public static function isDebug(): bool { return ($_ENV["APP_DEBUG"] ?? "false") === "true" && !self::isProduction(); }
    public static function logLevel(): string { return $_ENV["LOG_LEVEL"] ?? "warning"; }
    public static function cacheDriver(): string { return $_ENV["CACHE_DRIVER"] ?? "redis"; }
    public static function appUrl(): string { return rtrim($_ENV["APP_URL"] ?? "https://localhost", "/"); }
}

// ── Application bootstrap order ───────────────────────────────
// 1. Load .env (Dotenv)
// 2. Configure error reporting (based on APP_ENV)
// 3. Set up logging (Monolog, based on LOG_LEVEL)
// 4. Start session (with security settings)
// 5. Build dependency container
// 6. Add security headers
// 7. Start router and dispatch request

// ── .gitignore - never commit secrets ─────────────────────────
# .gitignore
# .env
# .env.*
# !.env.example    ← commit the EXAMPLE without real values
# vendor/
# storage/logs/
# storage/uploads/
# storage/cache/
# composer.lock    ← commit this (reproducible installs)

# .env.example - committed to git, no real values
# APP_NAME="My Blog"
# APP_ENV=development
# APP_DEBUG=true
# DB_DSN="mysql:host=localhost;dbname=blog;charset=utf8mb4"
# DB_USER=root
# DB_PASSWORD=
# ...

Quick Quiz

Tip

Tip

Practice Environment Configuration env Secrets Config Hierarchy in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Environment Configuration - .env, Secrets & Config Hierarchy

Practice Task

Note

Practice Task - (1) Write a working example of Environment Configuration env Secrets Config Hierarchy from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Environment Configuration env Secrets Config Hierarchy is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done