Creating Configuration Files in PHP

Creating your own configuration files in PHP is a relatively simple process. You can do this using the include construct.

Example config.php

<?php
return [
    'db' => [
        'username' => 'admin',
        'password' => '',
        'dbname'   => 'testdb',
    ],
    'memcached' => [
        'server' => '127.0.0.10'
    ],
];

Now we can load the config file like so…

<?php
$config = include 'config.php';

echo $config['db']['username']; // admin

Using return allows us to load the config in any scope and store it in any desired variable wihtout having to rely on global variables.

Some people do the following…

<?php
$config = [
    'db' => [
        'username' => 'admin',
        'password' => '',
        'dbname'   => 'testdb',
    ],
    'memcached' => [
        'server' => '127.0.0.10'
    ],
];

and then load the config like so…

<?php
include 'config.php';

echo $config['db']['username']; // admin

However, this is bad because you’re relying on global variables. If you’re already doing this and want a cleaner solution it would be to include the file in a function and return the value from that function instead.

<?php
function loadConfig($fileName) {
    include $fileName;
    
    return $config;
}

$config = loadConfig('config.php');

echo $config['db']['username']; // admin