PHP config
last modified November 14, 2026
In this article, we show how to work with configuration files in PHP. We use
the hassankhan/config package, whose classes live in the
Noodlehaus namespace.
The hassankhan/config package is a lightweight configuration file
loader. It supports PHP, INI, JSON, XML, YAML, properties and serialized files.
It detects the format from the file extension, merges several files into one
configuration, and reads nested values with a dot notation.
Setting up PHP config
First, we install the necessary packages. The symfony/yaml
package is needed only if we work with YAML files.
$ composer require hassankhan/config symfony/yaml
We install two packages with Composer. The following composer.json
is the result; we have added the autoload section by hand to load
our own classes from the src directory.
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"require": {
"hassankhan/config": "^3.2",
"symfony/yaml": "^8.1"
}
}
This is the composer.json file. After we edit the autoload section,
we have to regenerate the autoloader with composer dump-autoload.
PHP config JSON example
In the first example, we read the configuration data from a JSON file.
{
"app": {
"port": 3000
},
"db": {
"host": "localhost",
"port": 27017,
"name": "ydb"
}
}
We have db.json in the config directory. It has two
top-level objects: app and db.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
$conf = new Config('config/db.json');
echo $conf->get('app.port'), "\n";
echo $conf->get('db.host'), "\n";
echo $conf->get('db.port'), "\n";
echo $conf->get('db.name'), "\n";
echo $conf->get('db.user', 'guest'), "\n";
var_dump($conf->has('db.host'));
var_dump($conf->has('db.password'));
print_r($conf->get('db'));
echo $conf['db.name'], "\n";
We load the configuration file with the Config constructor.
The static Config::load method does the same. The values are
retrieved with the get method. The dot character is used to
go through the hierarchy of attributes.
The second argument of get is a default value, which is returned
when the key does not exist. The has method tests for the
existence of a key. When the key refers to a node, we get an array. The
configuration object also implements ArrayAccess, so we can read
a value with $conf['db.name'].
$ php read_json_cfg.php
3000
localhost
27017
ydb
guest
bool(true)
bool(false)
Array
(
[host] => localhost
[port] => 27017
[name] => ydb
)
ydb
PHP config YAML example
In the second example, we read configuration data from a YAML file.
app: port: 3000 db: host: localhost port: 27017 name: ydb
This is the db.yaml file.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
use Noodlehaus\Parser\Yaml;
$conf = new Config('config/db.yaml');
echo $conf->get('app.port'), "\n";
echo $conf->get('db.host'), "\n";
$conf2 = new Config('config/db.yaml', new Yaml());
echo $conf2->get('db.port'), "\n";
echo $conf2->get('db.name'), "\n";
The example reads the configuration from the db.yaml file. The
format is recognized from the .yaml extension, so we do not have
to say anything about the parser.
$conf2 = new Config('config/db.yaml', new Yaml());
When a file has an unusual extension, we can provide the parser explicitly in the second parameter.
$ php read_yaml_cfg.php 3000 localhost 27017 ydb
PHP config INI example
INI files are supported through the PHP parse_ini_file
function. Sections become nested keys.
[server] host = example.com port = 8080 debug = true [mail] from = admin@example.com
This is the server.ini file with two sections.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
$conf = new Config('config/server.ini');
echo $conf->get('server.host'), "\n";
var_dump($conf->get('server.port'));
var_dump($conf->get('server.debug'));
echo $conf->get('mail.from'), "\n";
$port = (int) $conf->get('server.port');
$debug = filter_var($conf->get('server.debug'), FILTER_VALIDATE_BOOLEAN);
var_dump($port, $debug);
The example reads the keys of the server and mail
sections. INI values are strings: the port is "8080" and the
boolean true is read as "1". We convert them
with a cast and with filter_var. JSON and YAML keep the types.
$ php read_ini_cfg.php example.com string(4) "8080" string(1) "1" admin@example.com int(8080) bool(true)
PHP config PHP files and environment variables
A PHP configuration file is a script that returns an array. Because it is code, it can read environment variables, which is useful for secrets and for settings that differ between servers.
<?php
return [
'debug' => true,
'timezone' => 'Europe/Bratislava',
'cache' => [
'driver' => 'file',
'ttl' => 3600,
],
'db' => [
'host' => getenv('DB_HOST') ?: 'localhost',
'port' => (int) (getenv('DB_PORT') ?: 5432),
],
];
The db.host and db.port values come from the
DB_HOST and DB_PORT environment variables and fall back
to defaults when they are not set.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
$conf = new Config('config/settings.php');
echo $conf->get('timezone'), "\n";
echo $conf->get('cache.ttl'), "\n";
echo $conf->get('db.host'), ':', $conf->get('db.port'), "\n";
var_dump($conf->get('debug'));
The program loads the file and prints some of the values. We run it twice; the second time we set the two environment variables in the shell.
$ php read_php_cfg.php Europe/Bratislava 3600 localhost:5432 bool(true) $ DB_HOST=db.example.com DB_PORT=5433 php read_php_cfg.php Europe/Bratislava 3600 db.example.com:5433 bool(true)
PHP config set values
The set method changes or creates a value at runtime. The change
affects only the object in memory; the file is not touched.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
$conf = new Config('config/db.json');
$conf->set('db.host', 'db.example.com');
$conf->set('db.user', 'admin');
$conf->set('cache.enabled', true);
echo $conf->get('db.host'), "\n";
echo $conf->get('db.user'), "\n";
var_dump($conf->get('cache.enabled'));
echo json_encode($conf->all()), "\n";
We change db.host and create the new keys db.user
and cache.enabled. Missing intermediate nodes are created
automatically. The all method returns the whole configuration as
an array, which we print as JSON.
$ php set_values.php
db.example.com
admin
bool(true)
{"app":{"port":3000},"db":{"host":"db.example.com","port":27017,"name":"ydb","user":"admin"},"cache":{"enabled":true}}
Merging configuration files
The merge method combines two configuration objects. Values from
the second object override the values from the first one.
app: port: 3000 db: host: localhost port: 27017 name: ydb
This is the first configuration file.
version: 2.0-dev db: name: testdb
This is the second configuration file. It adds a new version key
and overrides db.name.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
$conf = Config::load('config/db.yaml');
$conf2 = Config::load('config/app.yaml');
$conf->merge($conf2);
echo $conf->get('db.host'), "\n";
echo $conf->get('db.port'), "\n";
echo $conf->get('db.name'), "\n";
echo $conf->get('version'), "\n";
In the example, we merge the two configuration files. We can access attributes
from both files with one object. The merge is recursive: only db.name
is replaced, while db.host and db.port are kept.
$ php merging.php localhost 27017 testdb 2.0-dev
Loading multiple files and directories
We do not have to call merge ourselves. The constructor accepts an
array of paths, or a directory, and merges the files in order.
{
"db": {
"host": "db.internal",
"name": "proddb"
},
"app": {
"debug": false
}
}
This is the local.json file, which holds the settings that differ on
one machine. It is loaded after db.json.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
$conf = new Config(['config/db.json', 'config/local.json']);
echo $conf->get('db.host'), "\n";
echo $conf->get('db.port'), "\n";
echo $conf->get('db.name'), "\n";
var_dump($conf->get('app.debug'));
echo "--------------------\n";
$conf = new Config(['config/db.json', '?config/missing.json']);
echo $conf->get('db.host'), "\n";
echo "--------------------\n";
$all = new Config('conf.d/');
echo json_encode($all->all()), "\n";
Later files override earlier ones, so db.host and
db.name come from local.json, while db.port
comes from db.json. A path that starts with a question mark is
optional; no exception is raised when the file does not exist, which makes it
easy to support an optional local override file.
In the last case, we pass a directory. All supported files inside it are loaded
in alphabetical order, here 10-app.json and 20-db.yaml.
Different formats can be mixed.
$ php multiple_files.php
db.internal
27017
proddb
bool(false)
--------------------
localhost
--------------------
{"name":"demo","debug":true,"db":{"host":"localhost","port":5432}}
Code configuration with AbstractConfig
We can specify the configuration defaults in code by extending
AbstractConfig.
<?php
declare(strict_types=1);
namespace App\Config;
use Noodlehaus\AbstractConfig;
class AppConfig extends AbstractConfig
{
protected function getDefaults(): array
{
return [
'host' => 'localhost',
'port' => 80,
'servers' => [
'host1',
'host2',
'host3',
],
];
}
}
The defaults are specified in the getDefaults method of our
AppConfig class, which is saved in src/Config/AppConfig.php
so that the PSR-4 autoloader can find it.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use App\Config\AppConfig;
$conf = new AppConfig([]);
echo $conf->get('host'), "\n";
echo $conf->get('port'), "\n";
echo $conf->get('servers')[0], "\n";
$conf = new AppConfig(['port' => 8080]);
echo $conf->get('host'), ':', $conf->get('port'), "\n";
The example reads the configuration from the code. The constructor takes an
array of values that override the defaults. In the second case, we override
only the port; the other values stay as they are.
$ php code_config.php localhost 80 host1 localhost:8080
Reading and writing configuration
A configuration can also be loaded from a string, and written back as a string or to a file in another format.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Noodlehaus\Config;
use Noodlehaus\Parser\Json;
use Noodlehaus\Writer\Yaml;
$json = '{"name": "demo", "version": 2, "tags": ["a", "b"]}';
$conf = Config::load($json, new Json(), true);
echo $conf->get('name'), ' ', $conf->get('version'), "\n";
$conf->set('version', 3);
echo $conf->toString(new Yaml());
$conf->toFile('/tmp/demo_config.yaml');
echo file_get_contents('/tmp/demo_config.yaml');
We pass true as the third argument to Config::load to
say that the first argument is a string and not a file name; in this case the
parser is mandatory. After changing a value, we convert the configuration to YAML
with toString and write it to a file with toFile.
The writer is chosen from the file extension. Writers for JSON, INI, XML, YAML,
properties and serialized data are provided.
$ php write_config.php
demo 2
name: demo
version: 3
tags:
- a
- b
name: demo
version: 3
tags:
- a
- b
Source
The hassankhan/config repository
In this article, we have shown how to read, merge, modify and write configuration files in PHP. See also the PHP JSON and PHP Composer and autoloading tutorials.
Author
List all PHP tutorials.