Skip to content

PHP Tutorial Include and Require

Configuration Files

Lesson 160 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Settings such as the site name, database host or items per page should live in one place. Then you change them once, not in twenty files.

A config file that returns an array

config.php
PHP
<?php
return [
    "app" => [
        "name" => "Code Corner",
        "debug" => false,
    ],
    "db" => [
        "host" => "127.0.0.1",
        "name" => "shop",
    ],
    "per_page" => 10,
];
index.php
PHP
<?php
$config = require __DIR__ . "/config.php";

echo $config["app"]["name"] . "\n";
echo $config["db"]["host"] . "\n";
echo $config["per_page"];
Output
OUTPUT
Code Corner
127.0.0.1
10

A small helper for nested keys

Typing $config["db"]["host"] everywhere is long. A helper accepts a dotted path.

index.php
PHP
<?php
function config(string $path, mixed $default = null): mixed
{
    static $config = [
        "app" => ["name" => "Code Corner"],
        "db" => ["host" => "127.0.0.1"],
    ];

    $value = $config;

    foreach (explode(".", $path) as $key) {
        if (!is_array($value) || !array_key_exists($key, $value)) {
            return $default;
        }
        $value = $value[$key];
    }

    return $value;
}

echo config("db.host") . "\n";
echo config("db.port", 3306);
Output
OUTPUT
127.0.0.1
3306

Keep secrets out of the repository

Settings like the database password and API keys must not be committed to Git. Two common ways:

  1. Read them from environment variables (see Environment Variables).
  2. Keep a private config file outside the repository, and list it in .gitignore.
config.php
PHP
<?php
return [
    "db" => [
        "host" => getenv("DB_HOST") ?: "127.0.0.1",
        "user" => getenv("DB_USER") ?: "root",
        "pass" => getenv("DB_PASS") ?: "",
    ],
];

Do not keep config in the public folder

If config.php is inside the web folder and PHP stops working for any reason, a visitor could download your settings as plain text. Put configuration above the public folder, so the server never serves it.

Constants or arrays?

Array in a filedefine() / const
Nested valuesEasyAwkward
Change per environmentEasyPossible
Available everywhereAfter loadingYes

Most modern projects use arrays (or environment variables) and pass them to the code that needs them.

lightbulb
Group by purpose
Put database, mail and app settings in separate keys. A reader finds what they need in seconds, and a typo in one group does not affect another.