Configuration Files & Secret Management

Committing passwords and API keys into your repository exposes them to anyone with access to your code. Separating configuration from code and injecting secrets at runtime solves this problem.

Environment variables

Most platforms allow you to set environment variables outside of your application. In PHP, use getenv() or the $_ENV superglobal to read them:

<?php declare(strict_types=1); $dsn = getenv('DB_DSN'); $user = getenv('DB_USER'); $pass = getenv('DB_PASS'); $pdo = new PDO($dsn, $user, $pass); ?>

Store environment variables in your web server configuration or an orchestration tool like Docker Compose.

Dotenv files

During local development, storing settings in a .env file and loading them at runtime keeps your code clean. A simple parser might look like this:

<?php declare(strict_types=1); function loadEnv(string $path): void { foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) { if (strpos($line, '=') !== false) { [$key, $value] = explode('=', $line, 2); putenv(trim($key).'='.trim($value)); } } } loadEnv(__DIR__ . '/.env'); ?>

Never commit .env files to version control. Provide an example template like .env.example to document required variables.