PHP Configuration files

 

When ever you build a decent size application you will probably need to save configuration values. While you can hardcode configuration values this can make your code more brittle as you will have to update these configuration changes everywhere they are hardcoded when you want to update the value. Which could be quite a pain if this is stored in 10+ files!

The easiest way to get around this is by using PHP's built in configuration capacity.

To do this create your own configuration file, in this case its called config.ini.
DatabaseName = "phprocks"
Hostname = "localhost"
Username = "test"
Password = "password123"

This can then be read with the parse_ini_file function, like so:
$config = parse_ini_file("config.ini");
//will output phprocks
echo $config['DatabaseName'];

If you have a lot of configuration values this can be split down into sections so the config file would be modified to be:
[Database]
DatabaseName = "phprocks"
Hostname = "localhost"
Username = "test"
Password = "password123"
[Site]
SiteTitle = "PHP Rocks! - "

So to use the configuration file with sections you need to specify an extra parameter in the parse_ini_file function as shown below.
$config = parse_ini_file("config.ini", true);
//will output phprocks
echo $config['Database']['DatabaseName'];
This returns a multidimensional array which is why you must first specify the section you want so in the example above Database before the configuration element DatabaseName
Powered by Blogger.