PHP Configuration Storage


Ways to store configuration for a Web App written in PHP?
I've seen people use .ini, basic .php, etc.
Also, define() or simple global variables?
Most information as you can find.
Also, are databases good methods of storing configuration?

Best Solution

There is no “Best Way (tm)” to store your application configurations. It really all depends on your application, the kind of configurations, how often they can/need to change, and how easy you want to make it to change them.

Some people use a full singleton (or static) Config class for their application. Which looks something like this (with varying levels of complexity):


class Config

    protected static $config = array();

    private function __construct() {} // make this private so we can't instanciate

    public static function set($key, $val)
        self::$config[$key] = $val;

    public static function get($key)
        return self::$config[$key];


This is handy because you can call it wherever you want in your application with Config::set() or Config::get(). You then have a central place that your entire application is configured, and you can make it as complex or as simple as you like. You can back things up to the database, memcached, etc, whatever.

Which brings me to the next thing. Using the database is fine for things that need to be able to be changed on the fly and don't necessarily have to have an “initial setting”. An example would be site application customization features (eg. currency, background color, header image, etc). The problem here is, you have to load that every time a page is loaded in your application. So to solve that, you can use a middle layer caching technology (like memcached if you like). That would be fast, way faster than the database, but still adds overhead because you have to load it on every page load.

The fastest way, and consequently the “hardest” to change, is to use a config.php file or the like. This file would have $_GLOBALS array key definitions, or define()'s for values that you need access to throughout your application. This is fast because it's included in the request and hard coded in PHP, so all PHP has to do is interpret the file - no network IO or any added overhead other than the minimal overhead of including a file into your script. The things you’d store in these PHP files are things like your MySQL connection credentials, web service connection credentials, etc.

For an application which has a lot of users and a lot of customizations, you’ll probably need to deploy a ‘hybrid’ of the methods, or come up with your own. For something that is just a standard application deployment, you might be able to get away with a very simple config.php type approach.