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
<?php
return [
"app" => [
"name" => "Code Corner",
"debug" => false,
],
"db" => [
"host" => "127.0.0.1",
"name" => "shop",
],
"per_page" => 10,
];
<?php
$config = require __DIR__ . "/config.php";
echo $config["app"]["name"] . "\n";
echo $config["db"]["host"] . "\n";
echo $config["per_page"];
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.
<?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);
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:
- Read them from environment variables (see Environment Variables).
- Keep a private config file outside the repository, and list it in
.gitignore.
<?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 file | define() / const | |
|---|---|---|
| Nested values | Easy | Awkward |
| Change per environment | Easy | Possible |
| Available everywhere | After loading | Yes |
Most modern projects use arrays (or environment variables) and pass them to the code that needs them.