0

I'am using the parse_ini_file() function to parse my configuration file in PHP. The process_sections parameter is set to True because I need the sections.

[section 1]
key1 = value1
key2 = value2
...

[section 2]
...

What I'd like to do is to test if a section within an existing configuration file exists and if not I want to create it, along with the keys and values taken from an array, without overriding the other sections.

I know that in python there is a boolean method that allows to check it easily: config.has_section('my section'), and to create sections: config.add_section('my section').

I was wondering if there is something similar in PHP.

EDIT:

I found a simple solution but very effective. I used the array_key_exists('my section', $my_array) function which is similar to the python function I mentioned before and it does what I wanted. This is the simple code I have implemented

$config = parse_ini_file('MyConfigFile.cfg', True);

if (!array_key_exists('section 3', $config)) {
    foreach ($section_three_array as $key => $value) {
        $config['section 3'][$key] = $value;
    }
}

Then, to write back the new section (if it didn't exist) with its keys and values to the configuration file I used the function defined here.

Community
  • 1
  • 1
whatsup
  • 1
  • 2

1 Answers1

0

You can check a value exists using isset() and I recommend checking it also has a value with empty(). If you show some of your code we can advise on implementing those.

There's no native way to write back to the ini file, but here is a function someone else has made.

Community
  • 1
  • 1
bnx
  • 417
  • 5
  • 11