Constants may also be parsed
in the ini file so if you define a constant as an ini value before
running parse_ini_file(), it will be integrated into
the results. Only ini values are evaluated. For example:

Note

This function has nothing to do with the
php.ini file. It is already processed by
the time you run your script. This function can be used to
read in your own application's configuration files.

Notă:

If a value in the ini file contains any non-alphanumeric
characters it needs to be enclosed in double-quotes (").

Notă:
There are reserved words which must not be used as keys for
ini files. These include: null, yes,
no, true, false,
on, off, none.
Values null, off, no and
false result in "", and values
on, yes and true result
in "1", unless INI_SCANNER_TYPED mode is used (as of PHP 5.6.1).
Characters ?{}|&~!()^" must not be used anywhere in
the key and have a special meaning in the value.

Notă:

Entries without an equal sign are ignored. For example, "foo"
is ignored whereas "bar =" is parsed and added with an empty
value. For example, MySQL has a "no-auto-rehash" setting
in my.cnf that does not take a value, so
it is ignored.

Make sure you use double-quotes when using spaces in a value as of 5.3.

Consider the following INI file:

key = tested on php5

with the following code:

$res = parse_ini_file('myini.ini'); var_dump($res);

In 5.2, this will give you:

array(1) { ["key"]=> string(14) "tested on php5" }

In 5.3, this will give you:

Warning: syntax error, unexpected BOOL_TRUE in Unknown on line 1 in test.php on line 3 bool(false)

This is because the 'on' word is a reserved keyword for boolean TRUE. The documentation now states that a string that contains any non-alphanumeric character should be enclosed in double-quotes (a space is not alphanumeric).

If your configuration file holds any sensitive information (such as database login details), remember NOT to place it within your document root folder! A common mistake is to replace config.inc.php files, which are formatted in PHP:<?php$database['host'] = 'localhost';// etc...?>

With config.ini files which are written in plain text:[database]host = localhost

The file config.ini can be read by anyone who knows where it's located, if it's under your document root folder. Remember to place it above!

$myini = <<<EOT[examples] ; this is a section ; this is a comment line1 = intkey ; this is a int keynullvalue = null ; this is NULLtruebool = true ; this is boolean (TRUE)falsebool = false ; this is boolean (FALSE)intvalue = -1 ; this is a integer (-1)floatvalue = +1.4E-3 ; this is a float (0.0014)stringvalue = Hello World ; this is a unquoted stringquoted = "Hello World" ; this is a quoted stringapostrophed = 'Hello World' ; this is a apostrophed stringquoted escaped = "it work's \"fine\"!" ; this is a quoted string with escaped quotesapostrophed escaped = 'it work\'s "fine"!' ; this is a apostrophed string with escaped apostrophes

[[valid special cases]] ; this is a section with square brackets and whitespaces at the beginningquoted multiline = "line1line2line3" ; this is a quoted multiline stringapostrophed multiline = "line1line2line3" ; this is a apostrophed multiline string spaces before key = is ok ; this line has whitespaces at the beginningno val = ; this setting has no key= no key ; this setting has no value= ; this setting has no key and no value

[bad cases] ; you should never do that but it worksnotgood = unquoted"string ; this value has a single quotenotgood2 = unapostrophed'string ; this value has a single apostrophebad = "unclosed quotes ; this value has unclosed quotesbad2 = 'unclosed apostrophes ; this value has unclosed apostrophes

To those who were like me looking if this could be used to create an array out of commandline output I offer you the function below (I used it to parse mplayer output).

If you want it behave exactly the same as parse_ini_file you'll obviously have to add some code to feed the different sections to this one. Hope it's of help to someone!

<?php/** * The return is very similar to that of parse_ini_file, but this works off files * * Below is an example of what it does, where the first * value is what you'd normally want to do, and the second and third things that might * happen and in case it does it's good to know what is going on. * * $anArray = array( 'default=theValue', 'setting=', 'something=value=value' ); * explodeExplode( '=', $anArray ); * * the return will be * array( 'default' => 'theValue', 'setting' => '', 'something' => 'value=value' ); * * So the oddities here are, text after the second $string occurence dissapearing * and empty values resulting in an empty string. * * @return $returnArray array array( 'setting' => 'value' ) * @param $string Object * @param $array Object */function explodeExplode( $string, $array ){$returnArray = array();

Working on a project for a client recently, I needed a way to set a default configuration INI file, but also wanted to allow the client to override the settings through the use of a custom INI file.

I thought array_merge or array_merge_recursive would do the trick for me, but it fails to override settings in the way that I wanted. I wrote my own function to do what I wanted. It's nothing spectacular, but thought I'd post it here in case it saved someone else some time.

This allowed me to put the default INI file above the web root with information that requires extra security (database connection info, etc.) and a writable INI file within the structure of the site without affecting the default settings of the default config.ini file.

Unless the source code is freely available - and therefore the locations on INI files - there is no need to obfuscate or place INI files below DocumentRoot, as no one will know where they are. Otherwise, the .htaccess (or equivalent) to deny .ini files (or the config directory) is effective at preventing access.

And placing sensitive data in an INI file is just not a good idea in the first place. They are better off as defines (where, even if in a known location, can not seen):

<?phpeval("\$data['key9'] = {$data['key9']};");eval("\$data['key10a'] = \"{$data['key10a']}\";");eval("\$data['key11'] = {$data['key11']};");// example only - the values would have to be "checked" for// if/how they should be parsed// only to be used for "admin" only INI files?>

Instead of using parse_ini_file() function I would recommend to use PEAR's Config package which is MUCH more flexible (assuming that you don't mind using PEAR and OOP). Have a closer look at http://pear.php.net/package/Config

Not mentioned in docs about constants but 'magic' constants do NOT work. So for example:

// __DIR__ = /my/web/site/applog_file = __DIR__"/app.log"

Gives you just "__DIR__/app.log" with NO replacement.

Make sense it should NOT work as there would be question if it should be set to path of PHP file making the call or the path of the 'ini' file. Though the last might be useful the first generally would NOT be if you parse the file several different places in your code etc.

"Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing."

This core function won't handle ini key[][] = value(s), (multidimensional arrays), so if you need to support that kind of setup you will need to write your own function. one way to do it is to convert all the key = value(s) to array string [key][][]=value(s), then use parse_str() to convert all those [key][][]=value(s) that way you just read the ini file line by line, instead of doing crazy foreach() loops to handle those (multidimensional arrays) in each section, example...

ini file...... config.php

<?php

; This is a sample configuration file; Comments start with ';', as in php.ini

Please note that despite the changelog telling nothing about it, the parse_ini_file() changed -> the way it interprets the simple quote (not accepted on my 5.1 php)-> array index. PHP 5.3 accepts the following but not php 5.1

#If you want to replace a Setting in the ini, use this code:/// bool SetCMSSettings(string $Setting, string $replace, string $INI_PATH)/// $Setting = The Setting, which you want to replace/// $replace = the new value

Features : - support [] syntax for arrays- support . in keys like bar.foo.something = value- true and false string are automatically converted in booleans- integers strings are automatically converted in integers- keys are sorted when writing- constants are replaced but they should be written in the ini file between braces : {MYCONSTANT}

This is due to the function reading the URLs as a value, and failing when it finds that valid URL characters like '=' appear unescaped or the value unquoted as a whole. Since Windows does not escape them anyway, the solution is to scan it in raw mode, where it will read unparsed the value after the first '='. Since = only appears in URLs with parameters, this mistake may is not be obvious at a first glance.

I found another pitfall to watch out for. The key (to the left of the equal sign) can't be the same as one of the predefined values, like yes, no, on, off, etc. I was working on a script that read in an ini file that matched the country codes of top level domains to the full name of the country. I kept getting a parse error everytime it got to the entry for Norway ("no"). I fixed the problem by sticking a dot in front of each of the country codes.

I wrote a replacement function with following changes:-It allows quotes and double quotes.-It detects wether your .ini file has sections or not.-It will read until eof in any case, even if a line contains errors.

I know it can be improved a lot, so feel free to work on it and, please, notify me if you do.