PHP Logovlucas/phpdotenv

vlucas/phpdotenv is a robust PHP library that allows you to load environment variables from a `.env` file into PHP's `$_ENV`, `$_SERVER`, and `getenv()` superglobals. This approach, known as the 'Twelve-Factor App' methodology, advocates for storing configuration in the environment, separate from your codebase.\n\nWhy Use phpdotenv?\n1. Security: It prevents sensitive information (like database credentials, API keys, email server passwords) from being hardcoded directly into your application's source code, which could be accidentally committed to version control systems like Git.\n2. Environment Agnostic: It makes your application environment-agnostic. You can easily switch between development, testing, staging, and production environments by simply changing the `.env` file on each server without modifying the application's core code.\n3. Simplicity: It provides a straightforward way to manage configurations without complex configuration files or frameworks.\n4. Local Development: Developers can have their own `.env` files with local settings without affecting others or the production environment. Typically, the `.env` file is excluded from version control using a `.gitignore` entry.\n\nHow It Works:\nThe library works by reading a `.env` file (which is a plain text file containing key-value pairs) located at the root of your project or a specified path. Each line in the `.env` file represents an environment variable, like `DB_HOST=localhost` or `APP_DEBUG=true`. When `Dotenv::createImmutable()->load()` (or `createUnsafeImmutable()` for environments where `putenv()` is not available or desired) is called, it parses these lines and sets them as actual environment variables accessible via `$_ENV`, `$_SERVER`, and `getenv()`.\n\nKey Features:\n* Immutable Variables: By default, it uses `createImmutable()`, which throws an exception if you try to overwrite an already set environment variable. This promotes safer configuration. `createMutable()` is available for cases where overwriting is desired.\n* Required Variables: You can define variables that must be present in the `.env` file, ensuring essential configurations are not missed.\n* Variable Expansion: Supports variable expansion within the `.env` file (e.g., `APP_URL="https://${APP_DOMAIN}"`).\n* Comments and Blank Lines: Ignores lines starting with `#` (comments) and blank lines.\n* Quoting: Handles single and double quotes for values, and allows for values with spaces.\n* Path Specification: Allows specifying a custom path to the `.env` file, useful for monorepos or complex project structures.\n\nInstallation:\nphpdotenv is installed via Composer, the dependency manager for PHP.

Example Code

// To set up and run this example:\n// 1. Create a new directory for your project (e.g., `phpdotenv_example`).\n// 2. Navigate into that directory in your terminal.\n// 3. Create a `composer.json` file with the following content:\n/*\n{\n    "require": {\n        "vlucas/phpdotenv": "^5.0"\n    },\n    "autoload": {\n        "psr-4": {\n            "App\\": "src/"\n        }\n    }\n}\n*/\n\n// 4. Run `composer install` in your terminal. This will install phpdotenv and create the `vendor/autoload.php` file.\n\n// 5. Create a `.env` file in the same project root directory with the following content:\n/*\nAPP_NAME="My Awesome App"\nAPP_ENV=development\nAPP_DEBUG=true\nDB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=my_app_db\nDB_USERNAME=user\nDB_PASSWORD="your_secure_password"\nAPI_KEY="sk_live_xyz123abc" # This is a secret API key\nEMAIL_HOST=smtp.mailtrap.io\nEMAIL_PORT=2525\nEMAIL_USERNAME=some_user\nEMAIL_PASSWORD=some_password_here\n# An example of a variable using another variable\nFULL_APP_URL="https://${APP_ENV}.myawesomeapp.com"\n*/\n\n// 6. Create an `index.php` file in the same project root directory with the following PHP code:\n\n<?php\n\n// Require Composer's autoloader\nrequire __DIR__ . '/vendor/autoload.php';\n\n// Create a Dotenv instance\n// Pass the directory where your .env file is located. \n// In this example, it's the same directory as index.php.\n$dotenv = Dotenv\\Dotenv::createImmutable(__DIR__);\n\n// Load the environment variables\ntry {\n    $dotenv->load();\n    echo "Environment variables loaded successfully.<br>";\n} catch (Exception $e) {\n    echo "Error loading .env file: " . $e->getMessage() . "<br>";\n    exit(); // Exit if essential variables couldn't be loaded\n}\n\n\n// --- Now, access the environment variables ---\n\n// Accessing variables via $_ENV (common way)\necho "<h3>Application Settings:</h3>";\necho "App Name: " . ($_ENV['APP_NAME'] ?? 'N/A') . "<br>";\necho "App Environment: " . ($_ENV['APP_ENV'] ?? 'N/A') . "<br>";\necho "App Debug Mode: " . (isset($_ENV['APP_DEBUG']) ? ($_ENV['APP_DEBUG'] == 'true' ? 'Enabled' : 'Disabled') : 'N/A') . "<br>";\necho "Full App URL: " . ($_ENV['FULL_APP_URL'] ?? 'N/A') . "<br>";\n\necho "<h3>Database Configuration:</h3>";\necho "DB Connection: " . ($_ENV['DB_CONNECTION'] ?? 'N/A') . "<br>";\necho "DB Host: " . ($_ENV['DB_HOST'] ?? 'N/A') . "<br>";\necho "DB Port: " . ($_ENV['DB_PORT'] ?? 'N/A') . "<br>";\necho "DB Database: " . ($_ENV['DB_DATABASE'] ?? 'N/A') . "<br>";\necho "DB Username: " . ($_ENV['DB_USERNAME'] ?? 'N/A') . "<br>";\n// Sensitive data like passwords should be handled carefully and not echoed directly in production.\necho "DB Password: " . ($_ENV['DB_PASSWORD'] ?? 'N/A') . " (Should NOT be publicly displayed!)<br>";\n\necho "<h3>API Configuration:</h3>";\necho "API Key: " . ($_ENV['API_KEY'] ?? 'N/A') . " (Should NOT be publicly displayed!)<br>";\n\n// Accessing variables via getenv()\necho "<h3>Email Configuration (using getenv()):</h3>";\necho "Email Host: " . (getenv('EMAIL_HOST') ?: 'N/A') . "<br>";\necho "Email Port: " . (getenv('EMAIL_PORT') ?: 'N/A') . "<br>";\n\n// Example of requiring specific variables\ntry {\n    $dotenv->required(['APP_NAME', 'DB_HOST'])->notEmpty();\n    echo "<br>Required variables 'APP_NAME' and 'DB_HOST' are present and not empty.<br>";\n} catch (Exception $e) {\n    echo "<br>Error: " . $e->getMessage() . "<br>";\n}\n\n// Example of type casting for boolean and integer\n// Note: Values from .env are always strings. You need to cast them appropriately.\n$appDebug = filter_var($_ENV['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN);\n$dbPort = (int) $_ENV['DB_PORT'];\n\necho "<br>Type-casted values:<br>";\necho "App Debug (boolean): " . ($appDebug ? 'true' : 'false') . " (Type: " . gettype($appDebug) . ")<br>";\necho "DB Port (integer): " . $dbPort . " (Type: " . gettype($dbPort) . ")<br>";\n\n// Note: In a production environment, never expose sensitive environment variables directly in HTML output.\n// This example is for demonstration purposes only.\n?>