保存带注释的ini文件

I need to store some data in an ini file, and I have run into a problem. It is not hard to read the dat from the ini file, as php provides a built in function for that:

<?php
ini_parse();
?>

The problem is that I need to save data to the INI file, while (preferably) preserving commments. I would especially like to preserve this comment at the top:

;<?php die(); ?>

Im sure you can guess the reason for this, but in case you can't figure it out, I don't want this file to be requested directly. I would just like to read the INI values out of it using another php script.

However if there is not a way to preserve the comments, I still need to store data into the INI file, so I still need a class to save data to the INI file.

Does anyone know of a class that might do this?

This comment won't help you protect your file from being read in web browser, unless you configure your server to parse ini files as php source. Better idea is to place this file outside webroot, in password protected directory or configure one directory not to serve ini files.

As for writing data, this function will do for simple arrays:

function write_ini_file($file, array $options){
    $tmp = '';
    foreach($options as $section => $values){
        $tmp .= "[$section]
";
        foreach($values as $key => $val){
            if(is_array($val)){
                foreach($val as $k =>$v){
                    $tmp .= "{$key}[$k] = \"$v\"
";
                }
            }
            else
                $tmp .= "$key = \"$val\"
";
        }
        $tmp .= "
";
    }
    file_put_contents($file, $tmp);
    unset($tmp);
}

So array like this:

$options = array(
    'ftp_cfg' => array(
        'username' => 'user',
        'password' => 'pass',
        'hostname' => 'localhost',
        'port'     => 21
    ),
    'other_cfg' => array(
        'banned_emails' => array(
            'example@example.com',
            'spam@spam.gov'
        ),
        'ini_version' => 1.1
    )
);

Will be turned to:

[ftp_cfg]
username = "user"
password = "pass"
hostname = "localhost"
port = "21"

[other_cfg]
banned_emails[0] = "example@example.com"
banned_emails[1] = "spam@spam.gov"
ini_version = "1.1"

If your goal is to preserve the die(), the only way I know is to put it into a quoted value.

fake_value = "<?php die(); ?>";

I don't think it's possible to preserve comments using parse_ini_file(). You'd have to build your own parser for that. The User Contributed Notes on the manual page may be of help.

With an .htaccess file, you can deny the access to this file.