Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 62 ยท Configuration

Environment Variables and Secrets

Learn how Symfony loads .env files, uses env var processors like int and json, keeps passwords in the secrets vault, and debugs where a value comes from.

Some values must not live in your code: a database password, an API key, the address of a mail server. They differ between your laptop, the test server and production, and some of them must never reach Git. The standard answer, known from the Twelve-Factor App style of deployment, is to put them in environment variables and let the application read them at run time.

Symfony builds a small system on top of that idea. It reads .env files for convenience, gives you %env(...)% placeholders with processors that convert strings to integers, booleans or arrays, and offers an encrypted secrets vault for values you do want to commit safely. This lesson covers all three and the commands that tell you where a value came from. The real Symfony code is read-only. The runnable examples are plain-PHP stand-ins for the file parser and the processors.

How .env files are loaded

You met the file list in Project Structure. The order, from lowest to highest priority, is:

  1. .env: defaults for every environment, committed.
  2. .env.local: your machine's overrides, never committed. It is skipped when APP_ENV=test.
  3. .env.<env> (for example .env.dev): committed defaults for one environment.
  4. .env.<env>.local: your overrides for one environment, never committed.

Then real environment variables (set by the shell, Docker, the web server) win over every file, because Symfony's Dotenv component never overwrites a variable that already exists in the process. This is what lets a production server inject values without touching the code base.

flowchart TD
    A[".env"] --> B[".env.local<br/>(not in test)"]
    B --> C[".env.ENV"]
    C --> D[".env.ENV.local"]
    D --> E["Real environment variables<br/>always win"]
    E --> F["%env(NAME)% in config and services"]

Each layer overrides the previous one; real environment variables sit at the top.

A typical .env, with the safe defaults a new teammate needs to boot the project:

Terminal
# .env  (committed: no real secrets here)
APP_ENV=dev
APP_SECRET=

DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
MAILER_DSN=null://null
MESSENGER_TRANSPORT_DSN=doctrine://default

And your private .env.local (listed in .gitignore):

Terminal
# .env.local  (never committed)
APP_SECRET=0d8f3c1b5e7a4f6c9b2d1e0a8c7b6a59
DATABASE_URL="mysql://app:[email protected]:3306/blog?serverVersion=8.4&charset=utf8mb4"

The file syntax

The syntax looks like shell but is much simpler:

  • KEY=value per line; lines starting with # are comments.
  • Double quotes allow \n escapes and variable expansion; single quotes are fully literal (no expansion, use them for values containing $).
  • ${OTHER} inside an unquoted or double-quoted value is replaced by another variable's value, and ${VAR:-default} supplies a fallback when it is empty or missing.
  • Values may span several lines inside double quotes.

Symfony can even run commands with $(...), but this is rarely a good idea in a committed file because it makes boot slower and less predictable.

The first stand-in parses these rules, so you can see how expansion and quoting behave. It supports comments, single and double quotes, ${VAR} and ${VAR:-default}; it is a simplified Dotenv, not the real component.

PHP A tiny .env parser with expansion (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the real variable replaces DB_HOST even though the file defines it, and the expansion already sees the replacement. That is the same priority rule real Symfony uses.

Using variables in config: %env()%

In any config file you reference a variable with %env(NAME)%:

YAML
# config/packages/doctrine.yaml
doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'

# config/packages/framework.yaml
framework:
    secret: '%env(APP_SECRET)%'

Two details separate this from a normal parameter:

  • The value is read at run time, not baked into the compiled container, so you can change it without rebuilding the cache (the next request or process sees the new value).
  • Everything arriving from the environment is a string. You convert it with a processor, written as a prefix before the name.

Some of the most useful processors:

Placeholder Result
%env(int:HTTP_PORT)% "8080" becomes 8080
%env(bool:FEATURE_ON)% "1", "true", "on" become true; "0", "false" become false
%env(float:TAX_RATE)% "0.2" becomes 0.2
%env(csv:ALLOWED_HOSTS)% "a.com,b.com" becomes ['a.com', 'b.com']
%env(json:FEATURES)% JSON text becomes an array
%env(base64:SECRET_KEY)% decodes Base64
%env(trim:NAME)% trims whitespace
%env(file:KEY_FILE)% reads the contents of the file whose path is in the variable
%env(resolve:DATABASE_URL)% resolves %parameters% inside the value
%env(default:app.fallback:NAME)% uses the parameter app.fallback when NAME is not set

Processors can be chained, and they apply from right to left: %env(json:file:FEATURES_FILE)% first reads the file named by FEATURES_FILE, then decodes its JSON. There are more (url, query_string, key, const, enum, not, urlencode, require); the reference page for environment variable processors lists them all.

You can also inject a variable straight into a service with an attribute, with or without a processor:

PHP
<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class WelcomeMailer
{
    public function __construct(
        #[Autowire(env: 'MAILER_FROM')]
        private string $from,
        #[Autowire('%env(int:MAIL_BATCH_SIZE)%')]
        private int $batchSize,
    ) {
    }
}

A rule worth memorizing: read variables only through configuration or injection. Calling getenv() or reading $_ENV inside a service bypasses Symfony's processing, hides the dependency, and breaks when the container is cached with composer dump-env. Put the variable into config once and inject the result.

The second stand-in implements a processor chain. It is a simplified version of the real mechanism: placeholders are split by :, the last segment is the variable name, and the processors before it are applied from right to left.

PHP Env var processors with chaining (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the first two lines: the raw value is the string "8080", and only int: turns it into a number. Forgetting the processor is a classic cause of "expected int, got string" errors in typed constructors.

The secrets vault

Plain .env files are a poor home for a production password. If you commit it, anyone with repository access reads it. If you do not commit it, you need another way to ship it and to keep teammates in sync. Symfony's secrets vault solves this: secrets are stored encrypted in the repository, and only a private key on the server can read them.

Terminal
php bin/console secrets:generate-keys              # once per environment
php bin/console secrets:set DATABASE_PASSWORD      # asks for the value (hidden input)
php bin/console secrets:list --reveal              # shows names, and values if you may decrypt
php bin/console secrets:remove OLD_API_KEY

This creates config/secrets/<env>/ with a public key (it can only encrypt) and a private key (it decrypts), plus one encrypted file per secret. The rules that matter:

  • Commit the encrypted values and the public key, so every developer can add secrets.
  • The private key of prod is not committed. Put it on the server, or pass its contents in the SYMFONY_DECRYPTION_SECRET environment variable (base64-encoded). For the dev vault the private key is usually committed, because the values are harmless.
  • You use a secret exactly like an environment variable: %env(DATABASE_PASSWORD)%. Your config does not change when you move a value from .env to the vault.
  • For the live server, secrets:decrypt-to-local --force --env=prod writes a plain .env.prod.local-style file you can compile with composer dump-env prod, and secrets:encrypt-from-local goes the other way. Use them to migrate or to deploy to hosts without environment-variable support.

The vault is encryption at rest in your repository, with real keys kept apart from the code. It does not remove the need to protect the server itself: once the app is running, the decrypted values are in memory, and anyone who can run code on the server can read them. For larger setups, cloud secret managers (set as real environment variables by your platform) are a common alternative, and they work with the same %env()% placeholders.

Never put real production passwords in .env, in .env.prod, or in any other committed file. Those files are for defaults and development values. Use .env.local on a machine, real environment variables, or the vault.

Debugging where a value comes from

When the wrong value is used, ask Symfony instead of guessing:

Terminal
php bin/console debug:dotenv                       # every variable, and in which .env file it is defined
php bin/console debug:dotenv DATABASE              # filter by name
php bin/console debug:container --env-vars         # variables actually used by the container, with values
php bin/console debug:config doctrine dbal         # the resolved config of one package

debug:dotenv shows the load order and which files set each variable, which usually reveals a forgotten .env.local override. debug:container --env-vars lists only variables the config really references, with their processors and current values.

On a production server you can speed up boot by compiling all .env files into one PHP file once per deploy:

Terminal
composer dump-env prod      # writes .env.local.php

After that, the .env files are no longer parsed on each request, and real environment variables still win. Remember to rerun it when .env changes. The deployment lesson covers this in Performance and Deployment.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A variable DB_HOST is defined in .env, in .env.local and as a real environment variable. Which value does Symfony use?

    Dotenv never overwrites a variable that already exists in the process, so real environment variables win over all files.
  2. 2. What does %env(int:HTTP_PORT)% do when HTTP_PORT=8080?

    Environment variables are always strings. The int processor converts the value so typed constructors and config options receive an integer.
  3. 3. In %env(json:file:FEATURES_FILE)%, which step runs first?

    Chained processors apply from right to left: the file contents are read first, then decoded as JSON.
  4. 4. Which key must NOT be committed for the production secrets vault?

    The private key decrypts the secrets, so it stays on the server (or in SYMFONY_DECRYPTION_SECRET). The public key and the encrypted values are safe to commit.
  5. 5. Why is reading $_ENV['API_KEY'] inside a service discouraged?

    Config and injection make the dependency explicit and apply processors. Direct reads hide it and ignore Symfony's configuration.

Summary

  • Symfony loads .env, .env.local (not in test), .env.<env> and .env.<env>.local in that order, and real environment variables always win.
  • Use %env(NAME)% in config; the value is read at run time and is always a string unless you add a processor such as int:, bool:, csv:, json: or file:.
  • Processors can be chained and apply from right to left; #[Autowire(env: 'NAME')] injects a variable directly.
  • The secrets vault stores encrypted values in the repository; commit the public key and the encrypted files, keep the production private key on the server.
  • Find the source of a value with debug:dotenv, debug:container --env-vars and debug:config; compile production variables with composer dump-env prod.

Next up: Forms: Building and Rendering.