How to Create a Config File in PHP

How to Create a Config File in PHP

I like to use config files in my PHP (or any language) applications because I find it convenient to have a single place where all of my application settings are stored. This comes in handy when a setting needs to be changed that is used throughout your application because you do not need to search and replace many files in your application to make the change.

Creating a config.php file and including it in your application is easy, but not many people do it the right way.

How many times have you seen something like this in a config file?

<?php
$db_host = 'localhost';
$db_name = 'database';
$db_user = 'username';
$db_pass = 'password';
?>

Then, you include it and all of the variables are referenced as globals.

<?php
include('config.php');
echo $db_host; // 'localhost'
?>

The problem with this approach is you are introducing global variables into your project. Why is this bad? Because, global variables can conflict with local variables by mistake, or multiples files could create a global with the same name, but each wanting a difficult value.

How to Create a config.php File

I’m not a fan of using global variables when they can be avoided, so here’s an alternative that gives you much more flexibility with your config files.

<?php
return [
    'host' => 'localhost',
    'name' => 'database',
    'user' => 'username',
    'pass' => 'password'
];
?>

Simply returning the array allows you to include it into any variable you choose, which is much nicer than cluttering the global namespace with your config.

<?php
$database = include('config.php');
echo $database['host']; // 'localhost'
?>

A Better config.php

Of course, you can return any data you want with this approach — even a multidimensional array. Of course, you can return any data you want with this approach, but I prefer to return a multidimensional array with my related configs grouped under they own key name. This creates sort of a mini namespace for my configs.

<?php
return [
    'database' => [
        'host' => 'localhost',
        'name' => 'database',
        'user' => 'username',
        'pass' => 'password'
    ],
    's3' => ...
];
?>
<?php
$config = include('config.php');
echo $config['database']['host']; // 'localhost'
?>

Look! We didn’t create any globals and have access to all of our configs! This is by far my favorite way to write config files in PHP.