Articles

The month of PHP functions : INI manipulations

  • Ecrit par Rodolphe Eveilleau
  • vendredi 20 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 



.INI files are a text configuration file, which gathers parameters for an application. It is a fairly popular format, and PHP has a dedicated function to read the natively : parse_ini_file(). Give it the path to your configuration .INI file, and it will read it directly as an array.
Fichier INI : config.ini
[db]
host = "localhost"
username = "foo"
password = "bar"
 
 
[session]
save_path = "temp/sessions"

I recommand to always use double quotes, to enclose the values.

A .INI file may be divided into sections, identified by their square brackets. When using true as second parameter for the  parse_ini_file() function, one can access to those sections.

Example n°1 : Reading a hierarchised INI file
<?php
 
 
$config = parse_ini_file('config.ini', true);
 
 
print_r($config);
 
 
/**
 * Result: 
 *
 * array(2) {
 *  ["db"]=>
 *  array(3) {
 *    ["host"]=>
 *    string(7) "serveur"
 *    ["username"]=>
 *    string(3) "foo"
 *    ["password"]=>
 *    string(3) "bar"
 *  }
 *  ["session"]=>
 *  array(1) {
 *    ["save_path"]=>
 *    string(13) "temp/sessions"
 *  }
 * }
 * 
 */
 
 
?>

 When the file does not exists, the function will generate a warnin, and return an empty array. It is highly recommanded to check the return of this funciton.

Exemple n°2 : Checking INI return

<?php
 
 
ini_set('display_errors', 0);
 
 
if (!$config = parse_ini_file('config.ini', true)) {
    /**
     * Couldn't read the configuration file!
     */
}
 
 
?>

Error message handling

To get rid of the warning, one can suppress error display with the PHP directive display_errors. Using the operator @ is not recommanded. By changing this directive, all errors will be masqued. I do not use error_reporting(0), as I want to know about those error, and have them recorded in the logs.

Security

It is highly recommanded to put the configurations files outside the web root. This will prevent anyone to reach the configuration file, as it will be published as is, in clear text. If you have no other choice, use a .htaccess and add this :
<files *.ini>
  order deny,allow
  deny from all
</files>

Writing a .INI file

When you have modified the configuration after having read it, you need to write it back to the .INI file. The following function will do it for you :
<?php
 
 
function write_ini_file($path, $assoc_array) {
 
 
    foreach ($assoc_array as $key => $item) {
        if (is_array($item)) {
            $content .= "\n[$key]\n";
            foreach ($item as $key2 => $item2) {
                $content .= "$key2 = \"$item2\"\n";
            }       
        } else {
            $content .= "$key = \"$item\"\n";
        }
    }       
   
    if (!$handle = fopen($path, 'w')) {
        return false;
    }
    
    if (!fwrite($handle, $content)) {
        return false;
    }
    
    fclose($handle);
    return true;
}
 
 
?>

 Note : this function will return true or falsel.

Example n°3 : saving a new configuration
<?php
 
 
/**
 * Initial configuration
 */
$config = parse_ini_file('config.ini', true);
 
 
if (!empty($_POST['enregistrer_configuration'])) {
    $_CLEAN['save_path'] = filter_save_path($_POST['save_path']);
    /**
     * New configuration
     */
    $config['session']['save_path'] = $_CLEAN['save_path'];
 
 
    /**
     * Saving the configuration
     */
    write_ini_file('config.ini', $config);
}
 
 
?>

 Never forget to filter your external data, such as $_POST['save_path'] before using them. Also, make sure the writing function return true.

Keep in mind :
  • parse_ini_file() : Available since PHP 4.
  • INI on Wikipedia : http://en.wikipedia.org/wiki/INI.
  • Since PHP 4.2.1, this function is also affected by safe mode and open_basedir.
  • Since PHP 5.0, this function also include new lines in the read values
  • If a value in the .INI containt non alpha-numeric chars, it must be enclosed by double quotes.
< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter