Courses/PHP/Environment Management

    Lesson 37 • Advanced

    Environment Management 🔐

    Manage configuration safely with .env files, build config services, and handle environment-specific settings for dev, staging, and production.

    What You'll Learn in This Lesson

    • • Why hardcoded credentials are dangerous
    • • Parse .env files with vlucas/phpdotenv
    • • Build a typed config service with defaults
    • • Manage different environments (dev/staging/prod)
    • • Keep secrets out of git with .env.example patterns

    .env Files & Typed Access

    The .env file stores key-value pairs that change between environments. The vlucas/phpdotenv package loads these into $_ENV and getenv(). Always provide defaults for non-critical settings and throw errors for required ones like database credentials.

    Try It: .env Parser

    Parse environment files with typed getters and validation

    Try it Yourself »
    JavaScript
    // Environment Variables & Configuration Management
    console.log("=== The Problem: Hardcoded Credentials ===");
    console.log();
    console.log("  // ❌ NEVER do this in real code:");
    console.log("  \$dbHost = 'production-db.aws.com';");
    console.log("  \$dbPass = 'super_secret_password_123';");
    console.log("  \$apiKey = 'sk-live-abc123xyz';");
    console.log();
    console.log("  Why it's dangerous:");
    console.log("  • Credentials in git history forever");
    console.log("  • Same creds for dev/staging/productio
    ...

    Config Services & Environments

    Organized applications group related settings into config files (database.php, mail.php, cache.php) that read from environment variables. This separates "what can change" (env vars) from "how it's structured" (config files), making deployments safe and predictable.

    Try It: Environment Comparison

    Compare dev, staging, and production configurations side by side

    Try it Yourself »
    JavaScript
    // Config Service Pattern & Environment-Specific Settings
    console.log("=== Config Service: Organized Configuration ===");
    console.log();
    
    class ConfigService {
      constructor(env) {
        this.env = env;
        this.configs = {};
      }
    
      register(name, config) {
        this.configs[name] = config;
        console.log("  📦 Registered config: " + name);
      }
    
      get(path) {
        let parts = path.split(".");
        let current = this.configs[parts[0]];
        for (let i = 1; i < parts.length; i++) {
          if (current ==
    ...

    ⚠️ Common Mistakes

    ⚠️
    Committing .env to git — Even if you delete it later, it's in git history forever. Add .env to .gitignore before your first commit.
    ⚠️
    Using env() in config files everywhere — Call env() only in config files, then use config('database.host') in your app. This enables config caching in production.
    💡
    Pro Tip: Use Dotenv::createImmutable() to prevent code from overwriting env vars — this ensures server-level env vars take priority over .env file values.

    📋 Quick Reference — Environment Management

    ConceptDescription
    .envEnvironment-specific config (never commit)
    .env.exampleTemplate showing required vars (commit this)
    getenv()PHP built-in to read environment variables
    phpdotenvLibrary to load .env files into PHP
    $_SERVERSuperglobal containing server env vars

    🎉 Lesson Complete!

    You can now manage configuration securely! Next, learn to integrate payment gateways like Stripe and PayPal.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service