Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The guide to configuration of PHP applications

DZone's Guide to

The guide to configuration of PHP applications

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

Configuration management is the organization of settings specific to an instance of a web application. While many programming languages have a clear distinction between source code and binary packages, in PHP the demarcation line is not so cut and dry. Editing a php script is really easy, as there is no compilation step to perform (opcode caching is transparent to the average developer and happens in the webserver and not prior to the distribution.) Moreover, non-PHP files dedicated to configuration must be carefully placed outside of the document root to prevent their possible download from malicious entities.

These two reasons have driven the first generations of PHP applications to harcode configuration in the same PHP scripts that perform the business logic. Parameters such as absolute paths and database passwords are examples of embedded strings which are often found in legacy PHP applications.

There are strong reasons to avoid hardcoding, however. External configuration files remove the duplication of parameters scattered in different PHP scripts, and concentrate in a single, standard place the information needed to run the application or to move it to a different hosting service.
Moreover, configuration and business logic have two different lifecycles. Configuration changes when some parameter is tuned or a new component is deployed; it is generally not changed very often on a production server.

The PHP application itself is a stateless package which is not different from other instances on other servers. The more the configuration and the state are isolated from the business logic scripts, the more the latter ones can be upgraded and swapped without the external users noticing. The upgrade of libraries and CMS is a typical situation where you want to upgrade as soon as possible (maybe following the announcement of a security patch), and the previous hacking of PHP files hinders a quick fix.

However, not all parameters are subjected to externalization: in the initial phase of development, before a user story that prescribes the possibility of configuration is implemented, arbitrary functional parameters are often hardcoded. This is by no means a limitation in the development phase, as subsequent refactorings can extract parameters such as cache size and folder names, or accepted mime types for files upload.
A particular case solved in modern versions of PHP is the definition of relative paths. Due to include() and require() statements, relative paths are often employed in different files from the one that originated them.
That said, PHP provides a trick for automatic configuration of absolute paths: the __FILE__ magic constant. This constant is translated to the absolute filename of every file that contains it, allowing the construction of unambiguos absolute paths without hardcoding:

<?php
echo dirname(__FILE__); // the directory which the file is in
echo realpath(dirname(__FILE__) . '/../'); // the parent directory

PHP 5.3 takes this further with the __DIR__ magic constant, which essentially is a shortcut for dirname(__FILE__). These constants are often used to set up the include_path and let scripts refer to a path relative to the base folder of the application. include_path is server-specific and wired in the php.ini in shared hostings, so modifying it with absolute paths generated at runtime is a powerful solution.

Here I will present the standard media for configuration files used in PHP applications. In particular, these formats are oriented to characters and lines, resulting in human-editable files. Though, there are some domain specific configuration files which are deployed in a binary form, primarily for performance and integration purposes, and seek the aid of external tools and compilers, like gettext for localization.


INI files


Although it is traditionally associated with Windows, the INI file format is natively supported by PHP and it powers the binary distribution itself: much of the server-wide configuration of the PHP interpreter is contained in the php.ini file.

The cited support is provided by the parse_ini_file() global function:

// config.ini
[sectionName]
directive = value
// config_ini.php
<?php
$config = parse_ini_file('config.ini', true);
var_dump($config);
// result
array(1) {
["sectionName"]=>
array(1) {
["directive"]=>
string(5) "value"
}
}
The functions ini_get() and ini_set() are related instead to the override of php.ini (INItialization) directives, and not to custom INI files.

XML files

XML is a lingua franca of the communication between different applications, and although it is verbose and criticized, it is really an improvement over the binary formats used in the past. PHP natively supports also the parsing of XML files, and their usage for configuration purposes:

// config.xml
<?xml version="1.0"?>
<config>
<sectionName>
<directive>value</directive>
</sectionName>
</config>
// config_xml.php
<?php
$config = new SimpleXMLElement(file_get_contents('config.xml'));
var_dump($config);
// result
object(SimpleXMLElement)#1 (1) {
["sectionName"]=>
object(SimpleXMLElement)#2 (1) {
["directive"]=>
string(5) "value"
}
}

The SimpleXML extension is enabled by default in PHP 5, so it should be available in nearly every web server on Earth. XML is not limited to configuration, and SimpleXML knowledge is also a good addition to your PHP toolbox. You don't even need an XML Schema definition!

Native PHP

PHP files can return a value when they are evaluated via include() or require(). The value can consist in any valid variable, and in particular a multidimensional array that contains a configuration (or a more complex object):
// config.php
<?php
return array(
'sectionName' => array(
'directive' => 'value'
)
);
// config_php.php
<?php
$config = include 'config.php';
var_dump($config);
// result
array(1) {
["sectionName"]=>
array(1) {
["directive"]=>
string(5) "value"
}
}

This is dangerous as a syntax error may stop the execution of the client PHP scripts; however it is useful for avoiding dumb repetition and generate part of the configuration on the fly. This configuration won't be usually human readable as the INI one. Beware of incorporating too much logic in configuration files: they are meant to separate custom settings from business logic, and throwing logic in them means you're back to square one.

For a common object-oriented interface over INI and XML configuration files, check out Zend_Config, the component of Zend Framework dedicated to configuration management. You have seen in this article though that is very simple to parse configuration files with native PHP features.

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}