PHP

Lesson 09

Configuration and secrets

Load configuration from the environment and fail clearly when required secrets are missing.

Good Code

config/database.php
<?php declare(strict_types=1);

$databaseUrl = getenv('DATABASE_URL');

if ($databaseUrl === false || $databaseUrl === '') {
    throw new RuntimeException('DATABASE_URL is required.');
}

return [
    'url' => $databaseUrl,
    'timeout_seconds' => 3,
];

Bad Code

config/database.php
<?php

return [
    'url' => 'mysql://root:secret-password@localhost/app',
    'timeout_seconds' => $_GET['timeout'] ?? 30,
];

Review Notes

What to review

Good Code

The good version reads a required secret from the runtime environment and fails during startup if it is missing.

Bad Code

The bad version commits credentials and allows a request value to influence infrastructure configuration.

Takeaways

  • Secrets should be runtime configuration, not strings committed next to application logic.