Parse ini files in PHP

Citește postarea în română

Share on:

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:

 1;config.ini
 2
 3[simple]
 4number = 1
 5another = 2
 6fraction = 0.2
 7
 8[escape]
 9path = /usr/bin/php
10url = https://blog.claudiupersoiu.ro
11error = '<a href="%path%">%error%</a>'
12
13[array]
141 = a
152 = b
163 = c

To parse the previous file:

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

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.

1$cache = var_export($config, true);
2
3file_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.