Claudiu Persoiu

Blog-ul lui Claudiu Persoiu

Archive for 12 March 2011

Parse ini files in PHP

without comments

Why “ini” files? Because there are more convenient! Most servers in the *nix world have “ini” or “conf” configuration files. In the PHP world there are preferred PHP configuration files, which are usually arrays. Wouldn’t be more elegant to have an ini file without PHP code in it?

Fortunately PHP has a couple of native functions just for that: parse_ini_file and parse_ini_string.

The principle is very simple, you give an configuration ini file as a parameter and it will return an array.

A little example:


number = 1
another = 2
fraction = 0.2

path = /usr/bin/php
url =
error = '<a href="%path%">%error%</a>'

1 = a
2 = b
3 = c

To parse the previous file:

$config = parse_ini_file('config.ini', true);

The second parameter specifies if the sections will become keys in the resulting array. Honestly I don’t think of a case when that wouldn’t be useful.

Seems slow? In fact for the file above is faster to parse then to include an array already parsed. The difference on my computer is ~0.00002s.

But the above file is not exactly big, so let’s get to a more serious ini file, like php.ini. Here the difference was bigger in favor of array, which won whit an advantage of ~0.0003, which means about half of parsing time that was ~0.0006s.

Taking into consideration that my computer is pretty fast and concurrent request can add an overhead for big files, sometimes it is useful to use a cache of the ini file.

Fortunately this is easy to do in PHP.

$cache = var_export($config, true);

file_put_contents('cache/config.php', "<?php\n\$config = " . $cache . ';');

Now you just need to include cache/config.php file and of course regenerate it when something changes in the ini file.

PHP should have write permissions for the cache directory.

Written by Claudiu Persoiu

12 March 2011 at 11:38 AM

Posted in PHP

Tagged with , ,


without comments

Subversionning can be good to you, if you know how to use it!


Written by Claudiu Persoiu

5 March 2011 at 9:16 AM

Posted in Diverse