Recommend this page to a friend! |
Classes of Christian Vigh | Extended Ini File | README.md | Download |
|
DownloadINTRODUCTIONWHAT IS THE PURPOSE OF THIS CLASS ?The IniFile class provides support for both reading, updating and writing back .ini files. A SHORT REMINDER ON .INI FILESThe .ini file format is maybe one of the simplest and easiest to parse file formats, when there is a need to store (not too complicated) application settings. This has been the preferred choice for the PHP engine (which stores its settings in the php.ini file), as well as it was on Windows platforms before the invention of the Registry and DotNet application settings. The format is really straightforward : parameters (which are called keys in this document) are grouped within sections, whose names are enclosed in square brackets. After the section name come parameter definitions, which are a list of key/value pairs separated by an equal sign ("=") belonging to that section. For example, the following defines a section named Network, containing two parameters, Listen and Port :
Parameter values are not typed ; there are just plain text that must be interpreted by the application. Parameters defined before the very first section name in the .ini file are put in a section whose name is the empty string. WHAT CAN THE INIFILE CLASS DO FOR YOU ?The IniFile class can :
WHY YET-ANOTHER-INIFILE PROCESSOR ?PHP provides reasonable support for reading .ini files using the ini\_get(), ini\_set(), parse\_ini\_file() and parse\_ini\_string() functions. However it completely lacks of support for modifying them on the fly and writing them back. Of course, you could use xml files for that, or store your settings in a Mysql table. But the .ini file format comes naturally when you need to store simple settings and document them in a human-readable format, as this is the case for php.ini. The other key feature is that the IniFile class preserve your comments and formatting when writing the contents back. You wouldn't want to see your comments garbled when you write back the contents of php.ini, isn't it ? .INI FILE SYNTAXThe IniFile class can process .ini files whose syntax is commonly defined on Windows platforms (and in the php.ini file...). It also provides support for extended notations which are described below. BASIC SYNTAXThe basic syntax follows the Windows specifications :
Section and key names are not case-sensitive. EXTENDED SYNTAXThe IniFile class accepts extended syntax with regards to the Windows implementation. The new syntactic items are described below. Note that this is a superset of the basic syntax, and cannot be disabled. COMMENTSComments can be either single-line or multiline :
SPECIFYING A KEY AND A VALUEBasically, a key/value pair is specified like this :
The key name can include spaces :
Note however that the key "MySetting" will be different from "My Setting". Empty values can be specified in two ways :
If you specify the same key twice in the same section, the second value will override the first one ; thus, the value of MySetting in the following example :
will be "setting value 2". Note however that if you programmatically modify the value of "MySetting", there is no guarantee on which occurrence of "MySetting" will be actually modified. Finally, multiline values can be specified as here-documents by adding the "<<" string after the equal sign :
A keyword can be specified after the string "<<" :
The "END" keyword is expected when no keyword is specified after the here-document string. The "<<<" string (as for PHP) can also be specified instead of "<<". Spaces around the here-document string are ignored. Note however that the end keyword must start at the beginning of the line ; no leading spaces are allowed. EXAMPLE .INI FILEThe following example shows a .ini file using all the extended features of the IniFile class :
DESIGN ISSUES
SAMPLE USAGEAn example script will read the settings in the following file, example.ini, update the LastUpdate entry of the [Results] section then add the Status key :
Here is the example.php script :
APIThe following sections list the IniFile API by category. LOADING IN-MEMORY .INI FILESYou can create an empty .INI file object by using the new operator ; however, if you have existing contents to be loaded, use one of these three static functions. It will create a IniFile object, load the contents you specified, and return a reference to the object :
Each of these functions accept a parameter, $separator, which is the character to be used for separating key/value pairs. The LoadFromFile method is used to load .ini file contents from the specified $file. The $load_option parameter can be one of the following :
The LoadFromString method is used to load .ini file contents directly from a string. LoadFromArray can be used for loading .ini file contents from an array of lines. SAVING .INI FILESThe following method is used to save .ini contents :
The $forced parameter determines the conditions for saving. Normally, the .INI file is saved if and only if the dirty flag is set (the dirty flag is set when you create/update/delete keys or sections). You can override this behavior and perform a forced save whatever the initial value of the dirty flag is, by setting this parameter to true. $file is optional if the IniFile instance was created using the LoadFromFile() method. However it will be required if :
MANIPULATING KEYS$value = $inifile -> GetKey ( $section, $key, $default = null ) ;Returns a reference to the specified key $key in section $section. If the key does not exist, the default value $default will be returned. Because a reference is returned, you can directly modify the key value :
There are a certain number of drawbacks to this approach that make it safer to use the SetKey() method :
$inifile -> SetKey ( $section, $key, $value, $comment\_before = null, $comment\_after = null ) ;Creates or updates the key $key in section $section with the specified $value. You can tell the IniFile class to insert comments before and after the key definition by specifying the $comment\_before and $comment\_after parameters. $inifile -> RemoveKey ( $section, $key, $clear\_comment\_before = true ) ;Removes the key $key from section $section. By default, comments that are present before the key definition are considered to document the definition itself and will be removed. If you want to override this behavior and keep the potential comments before the key definition, simply set the $clear\_comment\_before parameter to true. Returns true if the key was defined and false otherwise. $status = $inifile -> RenameKey ( $section, $old, $new ) ;Renames a key contained in the specified section, from $old to $new. This function returns true if the operation was successful, or false if one of the following conditions occurred :
In this case, the key will not be renamed. $inifile -> ClearKey ( $section, $key ) ;Clears a key value. This is the equivalent of calling :
Returns true if the key exists in the specified section, false otherwise. $status = $inifile -> IsKeyDefined ( $section, $key ) ;Returns true if the key $key is defined in section $section. MANIPULATING SECTIONS$sections = $inifile -> GetSections ( $regex = null ) ;Returns the list of section names defined in the .ini file. If a regular expression is specified for the $regex parameter, then the return value will be an associative array containing the following entries :
Don't specify any anchor or delimiter in the input string since the regular expression will be replaced by the following string :
Why such a feature ? suppose your .ini file contains a list of sections that start with a certain string :
You can retrieve their names like this :
On output, each element of the $sections array will contain :
The function returns an empty array if a pattern was specified but no section was found matching this pattern. $keys = $inifile -> GetKeys ( $section, $keys\_by\_reference = true, $regex = null ) ;Gets the key names/values defined the specified section. Returns an associative array whose keys are the .ini key names and whose values are the .ini key values. If the $keys\_by\_reference parameter is set to true, the returned values will be references to the actual ones, so that you can directly modify them without calling the SetKey() method. An optional regular expression can be specified to filter out the key names. Unlike the GetSections() method, it must be an expression accepted by the preg_match() function and it does not modify the shape of the returned result. $status = $inifile -> IsSectionDefined ( $section ) ;Returns true if the specified section is defined. $inifile -> RemoveSection ( $section, $clear\_comment\_before = true ) ;Removes the specified section from the .ini file, together with its contents. This method is a little bit different from the ClearSection() method, since it also removes the section name from the .ini file. If comments are present before the section definition, they are considered by default to belong to the section and will also be removed, unless the $clear\_comment\_before is set to false. $inifile -> RenameSection ( $old, $new ) ;Renames the section $old to $new. The function returns true if the operation was successful, and false if one of the following conditions occurs :
In this case, the section will not be renamed. $status = $inifile -> ClearSection ( $section ) ;Clears a section contents, without removing the section name from the .INI file. Returns true if the section exists, false otherwise. $result = $inifile -> GetAllKeys ( ) ;Returns all the sections and corresponding keys defined in the .INI file. The function returns an associative array corresponding to the sections defined in the .INI file ; the value of each item is itself an associative array whoses keys are key names and whose values are references to the actual key value. For example, given the following .INI file :
the function will return :
Since the key values are references to the actual value, you can directly modify a key's contents, as in the following example :
instead of calling :
Note however that in the first case, multiline values will not be correctly handled, so the direct modification of a value should only be used for single-line values. If you don't want to bother with single- or multi-line issues, simply call the SetKey() method. MISC PROPERTIES & METHODSPROPERTIESFile property :This property is used by the Save() method, when no filename is specified, as the output path for the .ini contents to be saved. Separator property :This property determines the string used to separate key names from their values. The default is the equal sign ("="). METHODS$contents = $inifile -> AsString ( )Returns the .ini file contents as a string. The following are equivalent :
$status = $inifile -> IsDirty ( )Returns true if the in-memory .ini file contents have been modified, false otherwise. Note that the IniFile class has no way to tell whether you modified key values using references or not. If you want to rely on the IsDirty() method, then use the SetKey() method to assign new values to keys. $inifile -> SetVariableStore ( [$section | $store | $array | $options]... )Defines a variable store for value expansion using the specified parameters (see the VariableStore class here : http://www.phpclasses.org/package/10048-PHP-A-class-to-store-variable-names-and-values-and-pr.html). The parameter list is highly polymorphic and can contain any combination of the following values, which are only named for convenience purpose :
Variables specified in multiple $section, $array and $store parameters are merged into the final variable store object. Variables with the same name will be overridden. Multiple $options parameters are merged. If no arguments are specified, then any existing variable store will be cancelled. INI FILE STRUCTURE MANIPULATIONThe following methods help you further manipulate in-memory .ini file contents. APPENDING DEFINITIONSYou can append .ini file definitions on an existing instance using the following methods :
They work the same as their LoadFromxxx() counterparts, except that they operate on an existing object. There are also methods for appending or inserting sections :
InsertSection() insert the section $section before $section\_before. AppendSection() inserts the section $section at the end of the .ini file. FORMATTING OPTIONSWhen writing back your .ini file contents to a file, you may want some "pretty-printing" action, for example aligning key/value definitions on the same column ; the SetAlignment() method can be used for that. It accepts the following values :
No alignment takes place. The .INI file will be written back as is.
Individual keys within a section will be aligned according to the longest key name in the section. For example :
will become :
Alignement will be performed at the file-level ; the above example will give :
You can call the AlignDefinitions() method to realign in-memory .ini file contents before saving them. If no parameter is specified, the last one specified for the SetAlignment() method will be used. You can retrieve the current alignment value with the GetAlignment() method. Note that the AsString() and Save() methods automatically realign the definitions. |