DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. The guide to configuration of PHP applications

The guide to configuration of PHP applications

Giorgio Sironi user avatar by
Giorgio Sironi
·
Apr. 20, 10 · Interview
Like (0)
Save
Tweet
Share
14.88K Views

Join the DZone community and get the full member experience.

Join For Free
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.

PHP application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • gRPC on the Client Side
  • Top 10 Best Practices for Web Application Testing
  • Important Data Structures and Algorithms for Data Engineers
  • 10 Easy Steps To Start Using Git and GitHub

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: