PHP application configuration

Whenever I build a PHP application that needs to be configured by the user in some way, I follow certain principles:

  1. Configuration happens in a configuration file
  2. The configuration file may not be checked into Git
  3. An example configuration shall be provided
  4. Provide default configuration values wherever possible

Overview

My web application's directory structure is usually as follows:

mywebapp/
+ .gitignore
+ data/
| + config.php
| + config.php.dist
| + config.default.php
+ src/
| + MyWebApp/
|   + ...
+ www/
  + index.php

Configuration file

I usually place the configuration file into the data/ directory with the name config.php.

This file path is listed in .gitignore, so that it cannot be checked into git accidentially and doesn't litter git status output. Doing a git pull is thus possible without affecting the user's configuration.

Example configuration

To make setup convenient for the user, my apps ship a distribution configuration file, data/config.php.dist. It contains the necessary options that need to be modified to make the application usable, as well as the most commonly changed options.

The user is required to copy data/config.php.dist to data/config.php for initial setup and modify it. When the user starts the application without doing so, a message is shown requesting him to do exactly that.

Default configuration

Having many configuration options lets a user adapt the web application to his tastes in many ways, but also confuse him during initial setup. Thus I like to keep config.php.dist as small as possible.

For additional configuration options, my applications usually have a config.default.php file that is loaded before the user configuration in config.php.

With that, I as an application author can add more configuration options to the application and provide sensible default values for normal users. Power users can sift through the default config file and copy the values they want to change into their config.php file.

Since config.default.php is not modified by the user, it may be extended and updated at any time without disrupting or overwriting the user's configuration.

Written by Christian Weiske.

Comments? Please send an e-mail.