Environment Variables and .env Configuration

Read PHP environment variables, validate config types, load .env safely in development, and keep secrets out of public files and logs.

Lesson 81 of 86Advanced10 min read

A database password, deployment mode, and service hostname should not require editing application source for each environment. Environment variables let a process receive those settings from its deployment. A .env file is a development convenience containing text assignments, but PHP does not automatically parse it. A maintained loader can make that file available under a documented policy. This reference explains getenv(), missing values, boolean parsing, secret protection, and configuration validation. You will turn raw environment strings into a small typed configuration object and learn why an ignored .env file still needs protection from the web server.

Know where configuration comes from

Environment variables belong to the process environment and are usually supplied by the shell, service manager, container, or hosting platform. getenv('DB_HOST') reads a named value and returns false when it is unavailable under its contract. $_ENV depends on PHP's variables_order and runtime configuration, so do not assume it always contains every process variable. $_SERVER may contain server-provided settings but has a different role. Pick one documented configuration access layer instead of mixing sources unpredictably. The web service may not inherit variables available in your interactive terminal. PHP-FPM and managed hosting can filter or explicitly pass environment values. Verify the intended runtime without printing confidential values to a public diagnostic page.

A .env file is not a native PHP feature

A file named .env does nothing by itself in ordinary PHP. A loader, often installed through Composer, parses it according to that library's syntax and precedence rules. Use a maintained library rather than eval() or treating the file as PHP. Keep the file outside the public document root where possible and exclude secret-bearing copies from version control. Provide an .env.example with placeholder keys and safe descriptions, not real credentials. Different loaders can handle quoting, interpolation, and immutable-versus-overriding behavior differently. Read the installed library's documentation and choose whether actual deployment variables take precedence. Production platforms often inject secrets directly, making a local .env unnecessary.

Validate strings into deliberate types

Environment values are text. The string 'false' is truthy in a simple PHP boolean cast because it is nonempty, so (bool) getenv('DEBUG') is an unreliable parser. Use FILTER_VALIDATE_BOOLEAN with FILTER_NULL_ON_FAILURE or an explicit allowed set to distinguish recognized true and false values from invalid text. Validate integer settings such as ports and batch sizes within appropriate ranges. Required credentials should fail when absent or empty rather than silently becoming defaults. Optional settings may have documented defaults that are safe for the environment. Build a typed configuration structure once at startup or request initialization, then pass it to services. This prevents scattered code from interpreting the same raw value differently.

Keep secret exposure paths in view

Ignoring .env in Git prevents new accidental commits but does not remove a secret already present in history. Exposed credentials need rotation through the appropriate service, not only deletion from the current file. A misconfigured static server can serve dotfiles, so verify direct access is blocked or avoid storing them under served directories. Backups, logs, screenshots, and command arguments can expose secrets too. Do not dump $_ENV or complete configuration objects into error reports. Separate public configuration such as a feature label from server-only secrets. Browser JavaScript can receive public settings deliberately, but anything sent to the client should be considered visible. Minimize which components can read credentials and control secret retention.

Apply environment changes through deployment lifecycle

A running process may retain its environment until restarted or replaced. Updating a platform secret does not always change an already-running worker immediately. Follow the host's rollout and reload procedure, then verify behavior using safe checks. A long-running queue worker may need restart for a new password or feature policy. Avoid changing environment variables in the middle of a request as a global communication mechanism. Prefer immutable configuration passed to services. Separate development, test, staging, and production settings so tests cannot accidentally contact live payment or mail services. An environment name alone is not a security barrier; verify credentials, hosts, and permitted actions independently.

Make configuration failures clear and early

Validate required settings before starting expensive work. A missing database password should produce a controlled configuration failure rather than a chain of confusing query errors. Log which key is missing without logging its secret value. Keep an example configuration synchronized with actual requirements and document valid ranges and defaults. Tests should cover missing, empty, malformed, and boundary values. For a boolean flag, test both 'false' and an invalid word so they do not become the same state accidentally. Configuration validation is not a substitute for service connectivity checks; a well-formed hostname can still be unavailable. Report those stages separately to make operations diagnosis straightforward.

Practice task and worked solution

Build a configuration loader for DB_HOST, DB_NAME, DB_USER, DB_PASSWORD, DEBUG, and IMPORT_BATCH_SIZE. The solution reads a documented source, requires nonempty database values, parses DEBUG with an explicit boolean rule, and validates a bounded positive batch size. Return a typed structure without logging secret values. Add a safe example file listing required keys and keep real .env outside public files and version control. Test missing password, DEBUG=false, DEBUG=maybe, and an excessive batch size. Explain how the web service receives variables separately from the developer's terminal and which restart procedure applies when production secrets rotate.

Continue learning

Review Composer, security, and PDO.

The PHP getenv reference documents process-environment access and missing-value behavior.

Environment Variables and .env Configuration Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Parse a boolean setting safely

This fixed-input CLI example demonstrates how a configuration parser handles text values. It does not read or print real deployment secrets.

The parser distinguishes recognized false values from invalid input. A direct boolean cast of the string false would produce the wrong application behavior.

PHP
<?php
function parseFlag(string $raw): bool {
    $value = filter_var($raw, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
    if ($value === null) throw new InvalidArgumentException('Invalid boolean setting');
    return $value;
}
foreach (['true', 'false', '0', 'maybe'] as $raw) {
    try {
        echo $raw . ': ' . (parseFlag($raw) ? 'enabled' : 'disabled') . PHP_EOL;
    } catch (InvalidArgumentException) {
        echo $raw . ': invalid' . PHP_EOL;
    }
}
Output
true: enabled
false: disabled
0: disabled
maybe: invalid

Environment Variables and .env Configuration FAQ

Does PHP load .env automatically?

No. A .env file is just a text file, and PHP ignores it unless code reads it. Use an explicit loader, such as the vlucas/phpdotenv package, or platform variables set by your server, container or hosting control panel.

Why is (bool) 'false' true?

Because environment values are always strings, and 'false' is a nonempty string. Only empty strings and '0' convert to false. Use filter_var($value, FILTER_VALIDATE_BOOLEAN), which understands 'false', 'off' and 'no'.

Is .gitignore enough protection?

No. It only stops the file being committed. You also need to prevent web access by keeping .env outside the public folder, and consider other exposure paths too, such as backups, error pages that dump the environment, and phpinfo() output.

Can secrets be sent to JavaScript?

No. Anything delivered to the browser is visible to its user through the page source or developer tools. Keep secrets on the server and let JavaScript call your own endpoint, which uses the secret on the user's behalf.

Environment Variables and .env Configuration Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choicemedium

A real .env was committed and later deleted. What is still required?

Environment Variables and .env Configuration Quiz

2 questions to check what you learned.

  1. What does getenv return for an unavailable named variable?

    • A guaranteed empty array
    • A new password
    • The string true always
    • false under its API contract
  2. Why avoid casting DEBUG='false' directly to bool?

    • A nonempty false string is truthy in PHP
    • PHP cannot use booleans
    • Environment variables are encrypted integers
    • The value disappears