Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way (coding-wise) to store system configuration in a PHP application?

Tags:

php

config

system

Note: Configuration are being kept in a PHP file, config.php.

I've seen this done differently, here's a short list of examples (I'm storing DB info in these examples):

Constants: global, readonly

define('DB_USER','user12');
define('DB_PASS','21user');

Using GLOBALS array: global, changeable, repetitive, mixed with other globals

$GLOBALS['DB_USER']='user12';
$GLOBALS['DB_PASS']='21user';

Using a non-global array but raised globaly: possibly worse than the 2nd option

$config=array(); ...

$config['DB_USER']='user12';
$config['DB_PASS']='21user';

... global $config;
    mysql_connect('localhost',$config['DB_USER'],$config['DB_PASS']);

Defining class properties: (global, enumerable)

class Config {
    public $DB_USER='user12';
    public $DB_PASS='21user';
}

Criteria/Options/Features:

  • ease of coding: you wouldn't want to check if the setting exists, or initialize it
  • ease of modification: a non-programmer/layman could easily modify the settings
  • stored in a clean place: not mixed with other variables (can be stored in a sub-array)
  • runtime modification: in some cases, other devs may easily modify existing settings

The configuration might need to be changed some time during the running of the system, so option 1 is already not viable. The third option is not too clean either.


While writing this, I'm getting a big warning on the discussion being subjective and closed. So please keep up to the topic and give valid reasons to your answers.


This is a pretty obvious question, and considering I'm well familiar with different answers, you might ask, why am I making all this fuss? The thing is, I'm developing a framework, and unlike another framework (*ahem* joomla *ahem*) I don't want to pass through their mistake of throwing in a miss-informed solution which ends up having to be changed/re-purposed in the future.


Edit: First of, the location of the config file does not concern me. I'll make sure people can easily change location, if they want to, but this will not be a requirement. First of, cheap webhosts does not allow doing this, secondly, as far as security goes, this is really not a good option. Why? Because, the framework needs to know where the config is. Really, security through obscurity does not work. I'd rather fix all RFI and XSS (for instance) than be paranoid on hiding the config file under several layers.

like image 661
Christian Avatar asked Oct 08 '10 05:10

Christian


1 Answers

Hard-coded data may not be an option where people doing reconfiguration are not code-adept. Consider using parse_ini_file().

like image 82
bcosca Avatar answered Oct 27 '22 11:10

bcosca