Create Ini File, Write Values in PHP

create ini file, write values in PHP

Found following code snippet from the comments of the PHP documentation:

function write_ini_file($assoc_arr, $path, $has_sections=FALSE) { 
$content = "";
if ($has_sections) {
foreach ($assoc_arr as $key=>$elem) {
$content .= "[".$key."]\n";
foreach ($elem as $key2=>$elem2) {
if(is_array($elem2))
{
for($i=0;$i<count($elem2);$i++)
{
$content .= $key2."[] = \"".$elem2[$i]."\"\n";
}
}
else if($elem2=="") $content .= $key2." = \n";
else $content .= $key2." = \"".$elem2."\"\n";
}
}
}
else {
foreach ($assoc_arr as $key=>$elem) {
if(is_array($elem))
{
for($i=0;$i<count($elem);$i++)
{
$content .= $key."[] = \"".$elem[$i]."\"\n";
}
}
else if($elem=="") $content .= $key." = \n";
else $content .= $key." = \"".$elem."\"\n";
}
}

if (!$handle = fopen($path, 'w')) {
return false;
}

$success = fwrite($handle, $content);
fclose($handle);

return $success;
}

Usage:

$sampleData = array(
'first' => array(
'first-1' => 1,
'first-2' => 2,
'first-3' => 3,
'first-4' => 4,
'first-5' => 5,
),
'second' => array(
'second-1' => 1,
'second-2' => 2,
'second-3' => 3,
'second-4' => 4,
'second-5' => 5,
));
write_ini_file($sampleData, './data.ini', true);

Good luck!

How to read and write to an ini file with PHP

The PEAR Config_Lite package can do almost all the work (both reading and writing) for you super-easily. Check it out here: http://pear.php.net/package/Config_Lite

Writing values to INI file

I'll try to explain first why your code doesn't work, compared to the other.

Your inifile-array is build up of a nested array, $array[section][item] = value. The first dimension has the section names. The second dimension is the name of the items in the sections. So $fbsettingsDB["location"] contains an array of items, of which "value" is one.

Implode doesn't check if the array is nested. It just takes the first dimension (the sections) and tries to treat their values as a string. Since those values are actually arrays of items, PHP just converts that to the text 'array'.

Apart from that, you can't just implode the whole array. Section names should be enclosed in square brackets, so there is a little more work to do in that regard too.

If you check the solution in the answer you referred to, you'll see that it contains a loop which takes care of the first layer, the sections.
The array of items of each section is converted separately with implode, which is then prefixed by the section name in square brackets, and the whole lot is appended to the end result.

So, your intention here: You don't want to set a value and write it back to file at once, but update multiple values and only write the end result to disk. Well, fortunately the function doesn't have to be atomic. It already performs three separate actions: loading from disk, modifying the data, and serializing it back to disk. Let's see if those can be isolated in separate functions:

Read the data. Well, hardly worth to make a function, but it may make your application somewhat more consistent if you use the same naming et cetera in a collection of related functions.

Note: I just wrote these from scratch. No PHP at hand to test, so they might contain minor syntactical errors.

So here it is:

// Loads ini file data
function config_read($config_file) {
return parse_ini_file($config_file, true);
}

Setting the config in the loaded data. Again, hardly worth to have a function, but it adds readability and hides how exactly the ini file data is built up, so you don't have to worry about implementation details when using it. Note that the array is passed by reference. The array you specify is updated. The function doesn't return a value.

// Update a setting in loaded inifile data
function config_set(&$config_data, $section, $key, $value) {
$config_data[$section][$key] = $value;
}

Then writing it:

// Serializes inifile config data back to disk.
function config_write($config_data, $config_file) {
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($config_file, $new_content);
}

Note that so far I didn't modify any of the code. I just wrapped it in separate functions. If you like, you could even call those functions in another function, so you still got the shorthand to write everything to disk at once. You'll have the original functionality, but without having duplicate code:

// Short-hand function for updating a single config value in a file.
function config_set_file($config_file, $section, $key, $value) {
$config_data = config_read($config_file);
config_set($config_data, $section, $key, $value)
config_write($config_file, $section, $key, $value);
}

So, now you got this collection of functions, you can decide which to use based on the situation. If you just want to update a single value, you might as well write this:

config_set_file("location.ini", "id", "value", $_POST['fbconfigid']);

But if you have multiple configs to set, you can do this:

// Load
$config_data = config_read("location.ini");
// Set multiple values
config_set($config_data, "id", "value", $_POST['fbconfigid']);
config_set($config_data, "location", "value", $_POST['something']);
config_set($config_data, "result", "value", $_POST['somethingelse']);
// Save
config_write($config_data, $config_file);

I can imagine you can add other shorthands, like config_set_array_file, which you could call like this.. I'll leave the implementation of this one to you for exercise. ;)

array_config_set_file($config_file, array(
"id" => $_POST['fbconfigid'],
"location" => $_POST['something'],
"result" => $_POST['somethingelse']));

And after that, you can poor all this into an IniFile class to make it even nicer. :)

PHP write to .ini file

You are not using right, you should be passing a multidimentional array instead:

$data = array(
'Server' => array(
'p_ip' => '192.168.10.100',
'p_port' => 80,
'p_password' => 1234,
),
'Variable' => array(
'string1_find' => 'Caution'
)
);
//now call the ini function from Soygul's answer
write_php_ini($data, 'file.ini');

Here is my output:

[Server]
p_ip = "192.168.10.100"
p_port = 80
p_password = 1234
[Variable]
string1_find = "Caution"

Notice that you need to create an extra array per new section and then you can start listing your custom definitions.

PHP Add to key in ini file

You could add this condition to check if there is a value inside "color" (key section) and append new value accordingly :

if (empty($config_data[$section][$key])) {
$config_data[$section][$key] = $value;
} else {
$config_data[$section][$key] .= ',' . $value;
}

Full code :

function config_set($config_file, $section, $key, $value) {
$config_data = parse_ini_file($config_file, true);
if (empty($config_data[$section][$key])) {
$config_data[$section][$key] = $value;
} else {
$config_data[$section][$key] .= ',' . $value;
}
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($config_file, $new_content);
}

create arbitrary values in php.ini

Have you looked at get_cfg_var( config_var )?

http://www.php.net/manual/en/function.get-cfg-var.php

I believe this is for retrieving custom variables from e.g. the servers php.ini file

How to parse and write .ini file in codeigniter PHP?

This is not a complete solution, but some corrections to do to your code

First thing : please avoid the ternary operator, your code must always be as clear as possible, also you haven't planned the case where your value is null/empty

please try as follow

foreach($val as $skey => $sval) {
$configPrefix = $skey . ' = ';

if (!is_null($sval) && !empty($sval)) {
if (is_numeric($sval)) {
$res[] = $configPrefix . $sval;
}
else if (is_string($sval)) {
$res[] = $configPrefix . "'" .
$sval . "'" ;
}
else {
// TODO Log/throw exception for your unhandled case ...
}
}
}

Also you didn't decomposed your $insert array by sections, so use this and adapt your code to write sections in your ini file

$insert = array(
'INIDetails' => array(
'SipUserName' => $this->input->post('SipUserName'),
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'UCServer' => $this->input->post('UCServer'),
'UCPassword' => $this->input->post('UCPassword')
),

'DialPlan' => array(
'DP_Exception' => $this->input->post('DP_Exception'),
'DP_Rule1' => $this->input->post('DP_Rule1'),
'DP_Rule2' => $this->input->post('DP_Rule2')
),

'Advanced' => array(
'OperationMode' => $this->input->post('OperationMode'),
'MutePkey' => $this->input->post('MutePkey'),
'Codec' => $this->input->post('Codec'),
'PTime' => $this->input->post('PTime'),
'AudioMode' => $this->input->post('AudioMode'),
'SoftwareAEC' => $this->input->post('SoftwareAEC'),
'EchoTailLength' => $this->input->post('EchoTailLength'),
'PlaybackBuffer' => $this->input->post('PlaybackBuffer'),
'CaptureBuffer' => $this->input->post('CaptureBuffer'),
'JBPrefetchDelay' => $this->input->post('JBPrefetchDelay'),
'JBMaxDelay' => $this->input->post('JBMaxDelay'),
'SipToS' => $this->input->post('SipToS'),
'RTPToS' => $this->input->post('RTPToS'),
'LogLevel' => $this->input->post('LogLevel')
)
);


Related Topics



Leave a reply



Submit