Config.php File

Never store config.php inside the public web root. Place it above the web root.

Correct structure:

/home/user/
├── public_html/    <-- Web root (DocumentRoot)
│   ├── index.php
│   └── style.css
└── includes/
    └── config.php  <-- Inaccessible via web browser

Your index.php then includes it using an absolute path:

<?php
require_once('/home/user/includes/config.php');
?>

WordPress is the most famous example of a config.php file, though they call it wp-config.php. It lives in the root of the installation (often inside public_html, which is a historical risk). It contains:

// wp-config.php (simplified)
define('DB_NAME', 'database_name');
define('DB_USER', 'database_user');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
define('WP_DEBUG', false);
$table_prefix = 'wp_';

WordPress adds a clever security trick: wp-config.php can be moved one directory above the web root, and WordPress will still find it. config.php

When working with config.php, follow these best practices:

  • Use environment variables:
  • Use a configuration management system:
  • config.php is commonly used in PHP applications as a central configuration file that stores settings required for the application to run. Typical responsibilities include database connection parameters, environment-specific settings (development, staging, production), application constants, error/reporting configuration, and third-party API keys or endpoints.

    This prevents naming collisions and makes your code more predictable.

    <?php
    // config.php
    return [
        'db' => [
            'host' => 'localhost',
            'name' => 'app_db',
            'user' => 'db_user',
            'pass' => 'db_pass'
        ],
        'app' => [
            'name' => 'My App',
            'debug' => true
        ]
    ];
    

    Using it:

    $config = require 'config.php';
    echo $config['app']['name'];
    

    For object-oriented projects, treat configuration as a class.

    <?php
    // Config/Config.php
    namespace App\Config;
    

    class Config private static $settings = [];

    public static function get($key, $default = null) 
        return self::$settings[$key] ?? $default;
    public static function load($file) 
        self::$settings = include $file;
    

    // Load it Config::load(DIR . '/settings.php'); $dbPassword = Config::get('db.password'); Never store config

    If your config file is huge (hundreds of settings), don't load everything on every request. Use lazy loading or split configs:

    config/
    ├── database.php
    ├── cache.php
    ├── mail.php
    └── app.php
    

    Only include database.php when you actually need the database.