How do I manage configuration across environments in PHP?

Managing configuration across different environments in PHP is essential for maintaining flexibility and security in your application. By separating environment-specific settings, you can ensure that your app runs smoothly in development, testing, and production environments. Here’s how you can effectively manage configurations in PHP:

Using Environment Variables

One common practice is to use environment variables. This allows you to set configuration options outside of your codebase, making it easy to change settings without modifying your code.

// Load environment variables from .env file (using vlucas/phpdotenv package) require 'vendor/autoload.php'; Dotenv\Dotenv::createImmutable(__DIR__)->load(); $dbHost = $_ENV['DB_HOST']; $dbUser = $_ENV['DB_USER']; $dbPassword = $_ENV['DB_PASSWORD']; $dbName = $_ENV['DB_NAME']; // Create a new PDO instance $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPassword);

Using Configuration Files

In addition to using environment variables, you can manage configurations using PHP files. You can create a configuration file for each environment and include the appropriate one based on the current environment.

// config/development.php return [ 'db' => [ 'host' => 'localhost', 'user' => 'dev_user', 'password' => 'dev_pass', 'dbname' => 'dev_db' ] ]; // config/production.php return [ 'db' => [ 'host' => 'prod_host', 'user' => 'prod_user', 'password' => 'prod_pass', 'dbname' => 'prod_db' ] ]; // Load the configuration file based on the environment $environment = getenv('APP_ENV') ?: 'development'; $config = require "config/{$environment}.php";

PHP configuration management environment variables configuration files PHP dotenv database configuration