PHPackages                             noiselabs/configparser - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. noiselabs/configparser

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

noiselabs/configparser
======================

A configuration file parser for PHP 5.3 heavily inspired by Python's configparser library

92.4k[1 issues](https://github.com/noiselabs/configparser.php/issues)PHP

Since Nov 25Pushed 7y ago3 watchersCompare

[ Source](https://github.com/noiselabs/configparser.php)[ Packagist](https://packagist.org/packages/noiselabs/configparser)[ RSS](/packages/noiselabs-configparser/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

ConfigParser - A Configuration File Parser for PHP 5.3
======================================================

[](#configparser---a-configuration-file-parser-for-php-53)

[![Build Status](https://camo.githubusercontent.com/59c5d3388d05007bf6d7c58641853ea9e7e8aae9bda0b865cf2a0799df0ade2f/68747470733a2f2f7472617669732d63692e6f72672f6e6f6973656c6162732f636f6e6669677061727365722e7068702e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/noiselabs/configparser.php)

What is ConfigParser?
---------------------

[](#what-is-configparser)

ConfigParser is a configuration file parser for PHP 5.3 heavily inspired by Python's [configparser](http://docs.python.org/dev/library/configparser.html) library.

The ConfigParser class provides a way to read, interpret and write configuration files with structure similar to what’s found in Microsoft Windows INI files.

Requirements
============

[](#requirements)

- PHP 5.3.2 and up.

License
=======

[](#license)

ConfigParser is licensed under the LGPLv3 License. See the LICENSE file for details.

Installation (Composer)
=======================

[](#installation-composer)

### 0. Install Composer

[](#0-install-composer)

If you don't have Composer yet, download it following the instructions on  or just run the following command:

```
curl -s http://getcomposer.org/installer | php
```

### 1. Add the noiselabs/configparser package in your composer.json

[](#1-add-the-noiselabsconfigparser-package-in-your-composerjson)

```
{
    "require": {
        "noiselabs/configparser": "dev-master"
    }
}
```

Now tell composer to download the package by running the command:

```
$ php composer.phar update noiselabs/configparser
```

Composer will install the bundle to your project's `vendor/noiselabs` directory.

Documentation
=============

[](#documentation)

Basic instructions on the usage of the library are presented below.

Supported INI File Structure
----------------------------

[](#supported-ini-file-structure)

A configuration file consists of sections, each led by a `[section]` header, followed by `name = value` entries..

Leading and trailing whitespace is removed from keys and values. Values can be omitted, these will be stored as an empty string.

Configuration files may include comments, prefixed by `;`. Hash marks (`#` ) may no longer be used as comments and will throw a deprecation warning if used.

Usage
-----

[](#usage)

### Autoloading classes (optional)

[](#autoloading-classes-optional)

*You may skip this section if you are using Composer.*

ConfigParser makes use of PHP namespaces and as such the usage of a autoloader libray is recommended. [Symfony](https://github.com/symfony/symfony) provides a great class loader available on [GitHub](https://github.com/symfony/ClassLoader).

To have Symfony's ClassLoader autoloading our classes create a `autoload.php` file and included it at the top of your scripts.

```

```

### Basic usage

[](#basic-usage)

First, take the following INI file as an example:

```
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[github.com]
user = foo

[topsecret.server.com]
Port = 50022
ForwardX11 = no

```

Using ConfigParser is as simples as:

```

```

### Using ConfigParser like an associative array

[](#using-configparser-like-an-associative-array)

Because it implements `ArrayAccess` the ConfigParser object can be used in a straightforward way:

```
$cfg = new ConfigParser();

$cfg->read('/home/user/.config/server.cfg');

// get values
echo $cfg['github.com']['user'];

// set options for the 'github.com' section
$cfg['github.com'] = array('user', 'bar');

?>

```

### Iterate

[](#iterate)

And because ConfigParser implements `IteratorAggregate` it is also possible to use `foreach` to loop over the configuration.

```
$cfg = new ConfigParser();

foreach ($cfg as $section => $name) {
    echo sprintf("Section '%s' has the following options: %s\n",
                $section,
                implode(", ", $cfg->options($section))
                );
}

```

### Loading multiple files at once

[](#loading-multiple-files-at-once)

This is designed so that you can specify a list of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the array will be read.

```
$cfg = new ConfigParser();

$cfg->read(array('/etc/myapp.cfg', '/usr/local/etc/myapp.cfg', '/home/user/.config/myapp.cfg');

```

### Parsing files without sections

[](#parsing-files-without-sections)

ConfigParser was designed to work with INI files with section tags. For simple files with just `option = value` entries `NoSectionsConfigParser` can be used.

```

```

### Supported Datatypes

[](#supported-datatypes)

ConfigParser do not guess datatypes of values in configuration files, always storing them internally as strings. This allows reading entries like `pager = false` and keeping values as it is (without any kind of boolean parsing).

This means that if you need other datatypes, you should convert on your own, or use one of these methods:

- Integers:

    ```
      $cfg->getInt('topsecret.server.com', 'Port');

    ```
- Floats:

    ```
      $cfg->getFloat('topsecret.server.com', 'CompressionLevel');

    ```
- Booleans:

    ```
      $cfg->getBoolean('topsecret.server.com', 'ForwardX11');

    ```

### Fallback Values

[](#fallback-values)

When using `get()` to pull a value from the configuration you may provide a fallback value in case that option doesn't exist.

```
// API: ConfigParser::get($section, $option, $fallback)

```

Please note that default values have precedence over fallback values. For instance, in our example the 'CompressionLevel' key was specified only in the 'DEFAULT' section. If we try to get it from the section 'topsecret.server.com', we will always get the default, even if we specify a fallback:

```
echo $cfg->get('topsecret.server.com', 'CompressionLevel', '3');
// prints 9

```

Customizing Parser Behaviour
----------------------------

[](#customizing-parser-behaviour)

### Loading a set of default options/values

[](#loading-a-set-of-default-optionsvalues)

You may create an array of key-value pairs and pass them to the constructor as the first argument. These option/values will be initially put in the DEFAULT section. This makes for an elegant way to support concise configuration files that don’t specify values which are the same as the documented default.

```
// define some defaults values
$defaults = array(
                'Compression' 		=> 'yes',
                'CompressionLevel' 	=> 9
                );

$cfg = new ConfigParser($defaults);

```

### Advanced configuration

[](#advanced-configuration)

ConfigParser includes a small set of internal options to change the way it writes to configuration files or if exceptions are to be raised.

- **delimiter** - The delimiter character to use between keys and values (when writing). Defaults to `= `.
- **space\_around\_delimiters** - Inserts (or not) a blank space between keys/values and delimiters. Defaults to `TRUE`.
- **linebreak** - The linebreak to use. Defaults to `'\r\n'` on Windows OS and `'\n'` on every other OS (Linux, Mac).
- **throw\_exceptions** - Use this option to disable exceptions. If set to false ConfigParser will write to the error log instead. Defaults to `TRUE`.

### Using a custom error logger

[](#using-a-custom-error-logger)

If you have disabled PHP exceptions (see above section) ConfigParser will use `error_log()` to record the exception message. In this scenario you may want to use a custom error logger instead of `error_log`, or even disable logging at all.

To override the original logger method just extend ConfigParser and replace `ConfigParser::log()` with your own implementation.

[Monolog](https://github.com/Seldaek/monolog) is a great logging library for PHP 5.3 and will be used as our custom logger in the following example.

```

```

Development
===========

[](#development)

Authors
-------

[](#authors)

- Vítor Brandão -  / [twitter](http://twitter.com/noiselabs) / [blog](http://blog.noiselabs.org)

Submitting bugs and feature requests
------------------------------------

[](#submitting-bugs-and-feature-requests)

Bugs and feature requests are tracked on [GitHub](https://github.com/noiselabs/noiselabs-php-toolkit/issues).

Acknowledgements
----------------

[](#acknowledgements)

Python's [configparser](http://docs.python.org/dev/library/configparser.html) library was used as a source of inspiration for this library, including documentation and docblocks.

[![Bitdeli Badge](https://camo.githubusercontent.com/b36e4651421f8920489cb442c03b96999cacad24cceceaf05fcb8c615d03e969/68747470733a2f2f64327765637a68766c38323376302e636c6f756466726f6e742e6e65742f6e6f6973656c6162732f636f6e6669677061727365722e7068702f7472656e642e706e67)](https://bitdeli.com/free "Bitdeli Badge")

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 97.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/e9b45b06004ca41f33b01643ea58854ede6df882d9d262318c13e77f738e8402?d=identicon)[noiselabs](/maintainers/noiselabs)

---

Top Contributors

[![vitorbrandao](https://avatars.githubusercontent.com/u/109226?v=4)](https://github.com/vitorbrandao "vitorbrandao (43 commits)")[![bitdeli-chef](https://avatars.githubusercontent.com/u/3092978?v=4)](https://github.com/bitdeli-chef "bitdeli-chef (1 commits)")

### Embed Badge

![Health badge](/badges/noiselabs-configparser/health.svg)

```
[![Health](https://phpackages.com/badges/noiselabs-configparser/health.svg)](https://phpackages.com/packages/noiselabs-configparser)
```

###  Alternatives

[aimeos/macro

Customize classes using closures

2.3k131.7k5](/packages/aimeos-macro)[nodejs-php-fallback/stylus

PHP wrapper to execute stylus node package or fallback to a PHP alternative

11135.5k4](/packages/nodejs-php-fallback-stylus)[cityofzion/neo-php

NEO blockchain implementation for PHP

152.0k](/packages/cityofzion-neo-php)[miraheze/rotten-links

A MediaWiki extension to show the state of all external links on the wiki.

101.5k](/packages/miraheze-rotten-links)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
