phpconfiguration-files

Creating a config file in PHP


I want to create a config file for my PHP project, but I'm not sure what the best way to do this is.

I have 3 ideas so far.

1-Use Variable

$config['hostname'] = "localhost";
$config['dbuser'] = "dbuser";
$config['dbpassword'] = "dbpassword";
$config['dbname'] = "dbname";
$config['sitetitle'] = "sitetitle";

2-Use Const

define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('TITLE', 'sitetitle');

3-Use Database

I will be using the config in classes so I'm not sure which way would be the best or if there is a better way.


Solution

  • One simple but elegant way is to create a config.php file (or whatever you call it) that just returns an array:

    <?php
    
    return array(
        'host' => 'localhost',
        'username' => 'root',
    );
    

    And then:

    $configs = include('config.php');