PHP 7: Maintaining and Upgrading Legacy Apps · Working in a Legacy PHP Codebase

Configuration and Environments

Move hard-coded settings and secrets into environment-based configuration.

Legacy apps frequently hard-code database passwords and URLs in config.php committed to Git, with different copies per server. Move secrets into environment variables (or a .env file loaded with vlucas/phpdotenv in development), keep a committed .env.example, validate required settings at startup, and rotate any credentials that were ever committed.

<?php
// bootstrap.php
require __DIR__ . '/vendor/autoload.php';

if (file_exists(__DIR__ . '/.env')) {
    Dotenv\Dotenv::createImmutable(__DIR__)->load();
}

$required = ['DB_DSN', 'DB_USER', 'DB_PASSWORD', 'APP_ENV'];
foreach ($required as $key) {
    if (empty($_ENV[$key] ?? getenv($key))) {
        throw new RuntimeException("Missing configuration: {$key}");
    }
}

Common pitfalls

  • Leaving old credentials in Git history after moving them out.
  • Production behavior differing because of untracked per-server config files.
  • Displaying configuration errors with secrets to users.

Key points

  • Secrets in environment, not Git
  • Validate config at startup
  • Rotate previously committed credentials

Further reading: The Twelve-Factor App: Config

Practice questions

After moving a DB password from config.php to an environment variable, what else must you do?

Answer

Rotate the password: the old one remains in Git history and any clone. Also check backups and CI logs.

Why validate configuration at startup?

Answer

Missing or malformed settings then fail fast with a clear error at deploy time, instead of causing obscure failures later in a request.

Open in the app to mark lessons complete, take notes and track your progress.