Config.php

Imagine you have 50 PHP files, each with a hardcoded database password. When it's time to rotate that password (as you should, regularly), you have to edit 50 files. With config.php, you edit one line in one file.

A poorly written config file is just a list of global variables. A well-written one uses arrays, constants, and logical grouping. Let's build a robust example.

<?php
// config.php - A modern, structured approach

// 1. Error Reporting (Environment specific) define('ENVIRONMENT', 'development'); // or 'production', 'staging'

if (ENVIRONMENT == 'development') error_reporting(E_ALL); ini_set('display_errors', 1); else error_reporting(0); ini_set('display_errors', 0); ini_set('log_errors', 1); ini_set('error_log', '/path/to/php-error.log'); config.php

// 2. Database Configuration (using an associative array) $config['db'] = [ 'host' => 'localhost', 'user' => 'app_user', 'password' => 'StrongP@ssw0rd!', 'name' => 'my_database', 'charset' => 'utf8mb4', 'port' => 3306 ];

// 3. Application Paths (Absolute paths are safer) define('ROOT_DIR', dirname(DIR)); // Go up one level from config folder define('APP_DIR', ROOT_DIR . '/app'); define('PUBLIC_DIR', ROOT_DIR . '/public');

// 4. Site Configuration $config['site'] = [ 'name' => 'My Awesome App', 'url' => 'https://www.myawesomeapp.com', 'timezone' => 'America/New_York' ]; Imagine you have 50 PHP files, each with

// 5. Security & Hashing $config['security'] = [ 'salt' => 'a-very-long-random-string-here', 'hash_cost' => 12 // for bcrypt ];

// Set timezone date_default_timezone_set($config['site']['timezone']); ?>

The primary purpose of config.php is to:

To ensure the effectiveness and security of config.php, follow these best practices:

If you have no choice but to keep it in the web root, use .htaccess to deny access: The primary purpose of config

<Files "config.php">
    Order Allow,Deny
    Deny from all
</Files>