Rajan
Rajan

Reputation: 2425

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

I am uploading a INI file in Codeigniter.

I file upload a file with some parameters but its values are blank, and i store the file and file-path in database.

Now, I want to let user write some values to that file.

So i open the file and let user add some values to it.

But when i save the file its doesn't get stored the way i want.

Current Result

SipUserName = ""
SipAuthName = ""
DisplayName = ""
Password = ""
Domain = ""
Proxy = ""
Port = ""
ServerMode = ""
UCServer = 123456
UCPassword = 123456
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS = ""
RTPToS = 123456
LogLevel = 123456

Expected Result:

[INIDetails]
SipUserName = 
SipAuthName = 
DisplayName = 
Password = 
Domain = 
Proxy = 
Port = 
ServerMode = 
UCServer = 123456
UCPassword = 123456

[DialPlan]
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456

[Advanced]
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS = 
RTPToS = 123456
LogLevel = 123456

Below is my code:

public function edit_ini($id)
{

    /*The ID wen get from View's URI*/
        $path = "./uploads/"; 

        $site = $this->session->userdata('site');
        /*Set the path to open the file*/

        $this->db->select('*');

        $this->db->where('site_key',$site);

        $this->db->where('id',$id);
        /*Here the id it the ID we got in URI from View*/

        $this->db->from('base_ini');

        $query = $this->db->get();

        $result = $query->row();

        $filename= $result->base_ini_filename;

        $path= $result->file_path; 

        echo $this->db->last_query();

        /*Setting the Path and the filename from database.*/

        file_get_contents($path.$filename); 


        /*Get All The Contents from that file*/

        $this->data['params'] = $this->parameter_m->get();
        /*Getting the parameters to display on view*/

        $this->data['parameters']   = parse_ini_file($path.$filename,true);


        $insert = 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'),
                        'DP_Exception'    => $this->input->post('DP_Exception'),
                        'DP_Rule1'        => $this->input->post('DP_Rule1'),
                        'DP_Rule2'        => $this->input->post('DP_Rule2'),
                        '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')





                    );


            $this->load->helper('file');


            $file = $path.$filename;


                    function write_php_ini($array, $file)
                    {
                        $res = array();
                        foreach($array as $key => $val)
                        {
                            if(is_array($val))
                            {
                                $res[] = "[$key]";
                                foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
                            }
                            else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
                        }
                        safefilerewrite($file, implode("\r\n", $res));
                    }

                    function safefilerewrite($fileName, $dataToSave)
                    {    if ($fp = fopen($fileName, 'w'))
                        {
                            $startTime = microtime(TRUE);
                            do
                            {            $canWrite = flock($fp, LOCK_EX);
                               // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
                               if(!$canWrite) usleep(round(rand(0, 100)*1000));
                            } while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));

                            //file was locked so now we can store information
                            if ($canWrite)
                            {            fwrite($fp, $dataToSave);
                                flock($fp, LOCK_UN);
                            }
                            fclose($fp);
                        }

                    }


        /*Inserting The Data into .ini File*/
        write_php_ini($insert,$file);

        /*Back to you index page id data is submmited*/
        if(isset($_POST['submit'] ))
        {
            redirect('customer/upload_ini/index');
        }

        $this->data['subview'] = 'customer/upload/edit_ini';
        $this->load->view('customer/_layout_main', $this->data);



}

I want to print the sections into file.

Upvotes: 3

Views: 1400

Answers (2)

Halayem Anis
Halayem Anis

Reputation: 7805

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')
        )
    );

Upvotes: 1

Jonh Doe
Jonh Doe

Reputation: 761

parse_ini_file(), and work on the associative array.

sample:

$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

you have to pass true as second argument to get correct format.

Upvotes: 0

Related Questions