When doing complex applications it’s often nice to have some sort of system for handling settings. PHP has a nice function called parse_ini_file which can be used to create a basic but still usable setting file feature. A simple class which loads the configuration file and offers some methods to retrieve the values for a given key is all that’s needed. The example I’m providing is pretty basic, but it’s still very usable and can be added to almost any application.

First, we need to create a file to hold the settings. It’s ordinary plaintext and follows the INI format.

Here is a quick sample of some key / value pairs:

[general]
locale = no_NO
company.name = MyCompany

datasource.host = localhost
datasource.database = mydb
datasource.username = user
datasource.password = 1234

The class for accessing the file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MyConfigClass{
  protected $config;
 
    public function __construct()
    {
      $this->config = parse_ini_file('../conf/myapp.ini');
 
    }
 
    public function getConfig($key = null)
    {
      if($key !== null)
      {
        if(isset($this->config[$key]))
        {
          return $this->config[$key];
        }
        else
        {
          throw new Exception("Unknown key '$key' in configuration");
        }
      }
      else
      {
        return $this->config;
      }
    }
 
    public function setConfig($config)
    {
 
      $this->config = $config;
    }
}
 
?>

Usage:

1
2
3
$configManager = new MyConfigClass();
 
$value = $configManager->getConfig['datasource.host'];

Now, when working on larger application one usually have a application like class, and that’s a nice place to put this code. When using Prado I usually place the config code in the TApplication class.

[tags]PHP[/tags]

19 Responses to “Simple config management for PHP”

  1. [...] Hoem on his blog posted article how you can use ini files for your php application configuration. It is very useful for bigger [...]

  2. You may want to have a look at the Configuration component of eZComponents:

    http://www.ezcomponents.org/docs/tutorials/Configuration

    It does not only give an interface to configuration files in INI and PHP Array format, but also handles grouping of configuration settings and preserves comments in the configuration files.

  3. Thomas: I’ve not tried it out yet, but it sure is interesting. I would expect to use this on larger scale applications, and the feature I posted in mid size perhaps? The EZ way seems a bit more complex at first.

  4. It’s not a lot more complex, it just has a few more features. Maybe you’re going to need more features in the end, so might be a good idea to use the component.

    Other frameworks such as the Zend Framework have similar components you could use.

    Personally, I’ve never really seen the advantage of ini files over a plain php file.

  5. Ivo: Thanks for commenting. I will definitely check it out. Not seen the Zend stuff yet, but will look into that as well. When it comes to ini files vs php files (at least in my case) we profit from using ini files. The reason for this is that .ini files are considered configuration files, while php files is code. Systech is happy when it comes to editing configurations, but not code ;)

  6. [...] a new post to his blog today, Eirik Hoem gives an example of using the parse_ini_file function to work with [...]

  7. Mostly as a note to the readers, as the writer probably knows this, but …

    For web applications, keep in mind that in most default setups ini files are returned to a browser in plaintext, meaning your database credentials can be exposed to anyone who happens upon your configuration file. Make sure you setup the appropriate rules to make sure access is denied to these ini files.

  8. I highly suggest you add some sort of caching to this (preferably via APC). Otherwise you’ll end up hitting the disk and parsing config files (of which there may be multiple) on every request.

  9. No fence, but I like the Zend_Config more :) Accessing config values as objects is a key to a great feeling.

    Example: $config->datasource->host

  10. In response to Jeremy,

    That is a great point, and something you should always try to be cognizant of as you set up your we projects. I find that one of the easiest ways to protect config files, whether, ini file format, or xml format, is to give them a .php extension. This way the server parses them as PHP (which ends up looking like a blank file to the browser). But your code doesn’t care what the extension is, as we are just working with a stream to a file, the extension is irrelevant. Only one way to go, but its a viable option for those who are not strong server administrators.

  11. We use ini files extensively for configuration info in our framework, but one thing to be mindful of if you’re storing sensitive info in there is to make sure it can’t be seen in the browser. You could do something in your config like this:

    Deny from all

    But we take an extra step I’d recommend taking as well:

    1) Make sure the files end in .php
    2) Add the following lines at the top and bottom:

    ;

    (Hopefully that renders okay :) Now if someone requests that in the browser, the site returns a blank screen with just “; ” on it. Hope that helps you out too.

  12. Looks like my examples didn’t make it through… Let’s try again:

    ; <?php /*

    ; */ ?>

  13. As a php noob…

    Why have the expense of instantiating an object each time for these static variable lookups, why not just include a config file?

    require_once “myConfig.inc.php”;

    Then just access the vars as normal? If overwriting is a concern you can always prefix with something like:

    $config_adminemail = “me@wherever.com”;

  14. [...] Simple config management for PHP (tags: php webdesign programming language configuration application classes) 06:32:47 pm on May 31, 2008 | # | [...]

  15. This configuration option is nice… but what about times when your configuration has to make a decision? For example, if I’m using the same code base over multiple partner websites, but the name is different, I need to make a choice on what name to display as the global one.

    INI files would allow you to have either 1) multiple INI files – kinda code duplication or 2) have them outside of the code base – which may make them naked to versioning software.

    I’ve found that I end up using a class with a static ‘get’ method – that creates a new instance of itself in singleton pattern – which performs all of the logic calculations.

    Keep up writing!
    -aaron

  16. [...] I’m really going to want to read from the things that will benefit me little. Today I read an article which I could have lived my life without reading, if only because that’s already how I do [...]

  17. [...] 30th 2008 9:32am [-] From: blog.eirikhoem.net [...]

  18. Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

  19. $value = $configManager->getConfig['datasource.host'];

    Shouldn’t that be ( ) brackets?

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">