How to write a ini file in PHP codeigniter? - php

Hi I want to write a ini file into php.
first i upload a ini file to my server then i edit it,
i want to make some changes in parameters then want save that file back to uploads.
I used put_file_contents and fwrite but didn't get required result.
this is my code:
$data = array('upload_data' => $this->upload->data());
foreach ($data as $info)
{
$filepath = $info['file_path'];
$filename= $info['file_name'];
}
$this->data['parameters'] = parse_ini_file($filepath.$filename);
$insert = array(
'OTAID' => $this->input->post('OTAID'),
'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'),
'ServerMode' => $this->input->post('ServerMode')
);
$this->load->helper('file');
$file =fopen($filepath.$filename,'w');
fwrite($file,implode('', $insert));
$this->data['subview'] = 'customer/upload/upload_success';
$this->load->view('customer/_layout_main', $this->data);

As I told you in the last question you will need to use a helper function to turn the array into the right format for an ini-file. You can find such a helper-function here.
Also you are loading the file-helper from codeigniter but using the php built-in methods. Please have a look to the docs here.

Something akin the following might work:
//Replace the fwrite($file,implode('', $insert)); with
$iniContent = "";
foreach ($insert as $key => $value) {
$initContent .= $key."=".$value.PHP_EOL;
}
fwrite($file,$iniContent);
Note: This is probably the simplest thing one can do. I doesn't deal with sections or comments or escape characters or basically any sort of error checking. If you expect this sort of thing to be done a lot in your code I suggest you look into existing INI reading/writing libraries.
Update
Try http://pear.php.net/package/Config_Lite or http://pear.php.net/package/Config as suggested at create ini file, write values in PHP (which also has a lot more information to look at for this particular issue).

Related

Upload multiple files at the same time without a duplicate in Laravel

I use this code to upload multiple files together in Laravel. However, all name files get duplicated. Please guide me.
if (is_array($files) || is_object($files)) {
foreach ($files as $file) {
$name = time().'.'.$file->getClientOriginalExtension();
$file->move(public_path('uploadmusic'), $name);
PostPhoto::create([
'post_id' => $post->id,
'filename' => $name
]);
}
}
1568314601.png
1568314601.png
1568314601.png
The precision of time() is only a second - not enough time to make time() report a different value when assigning $name in your loop for each file.
Append something else, like a call to \Illuminate\Support\Str::random() to get each name to be unique.
Depending on requirements, you might consider omitting the timestamp from the filename altogether and use something like md_file() instead.
$name = implode('.', [
md5_file($file->getPathname()),
$file->getClientOriginalExtension()
]);
This can also help keep duplicate files off of your storage device.

Properly reading the data of .csv files in php

I have a working system on which I get the data of two .csv file. And save all the data into array and then compare some of the data existing on both csv file. The system works well but later I found out that some of the rows doesn't display on the array. I think I don't use the proper code in reading a csv file. I want to edit/improve the system. This is my code on reading or getting the data from csv file.
$thedata = array();
$data = file("upload/payment.csv");
foreach ($data as $deposit){
$depositarray = explode(",", $deposit);
$depositlist = $depositarray;
$key = md5($depositlist[9] . $depositlist[10]);
$thedata[$key]['payment'] = array(
'name' => $depositlist[0],
'email' => $depositlist[1],
'modeofpayment' =>$depositlist[8],
'depositdate' => $depositlist[9],
'depositamount' => number_format($depositlist[10],2)
);
}
'<pre>',print_r($thedata),'</pre>';
//more code here for comaparing of datas...
1.) What is wrong with file("upload/payment.csv") when reading csv file?
2.) What is the best code in reading a csv file that is applicable on the
system, not changing the whole code. Should remain the foreach loop.
3.) Is fgetcsv much better for the existing code? What changes should be made?
Yes, You can use "fgetcsv" for this purpose.
The fgetcsv() function parses a line from an open file.This function returns the CSV fields in an array on success, or FALSE on failure and EOF.
check the examples given below
eg1 :
<?php
$file = fopen("contacts.csv","r");
print_r(fgetcsv($file));
fclose($file);
?>
eg 2:
<?php
$file = fopen("contacts.csv","r");
while(! feof($file))
{
print_r(fgetcsv($file));
}
fclose($file);
?>
Link : https://gist.github.com/jaywilliams/385876

Upload Multiple Files with FuelPHP

I currently have a script that allows me to upload 1 file to my server. It works great.
Here is a portion of the code I am using to do this:
// Custom configuration for this upload
$config = array(
'path' => DOCROOT.DS.'foldername/tomove/your/images',
'randomize' => true,
'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'),
);
Upload::process($config);
// if a valid file is passed than the function will save, or if its not empty
if (Upload::is_valid())
{
// save them according to the config
Upload::save();
//if you want to save to tha database lets grab the file name
$value = Upload::get_files();
$article->filename = $value[0]['saved_as'];
}
I was now wondering, how do I loop through multiple files and upload these to my server?
I'm guessing using a foreach loop but I'm a little out of my depth with this I'm afraid.
Ultimately, I plan to store these filenames in a separate table on my database.
Many thanks for any help with this.
You already have the result in your code.
You already store it
$value = Upload::get_files();
so
$value = Upload::get_files();
foreach($value as $files) {
print_r($files);
}
And you will get everything what you need

Errors while exporting to .xls using PHP

I've asked a similar question previously but Ive been told my question is just me being lazy so let me rephrase.
Ive been using a PHP class script to enable me to export my SQL data to a .xls file but the resultant excel file doesnt display any values and no error is being displayed on the webpage itself.
The class file Im using is documented in the link below:
http://web.burza.hr/blog/php-class-for-exporting-data-in-multiple-worksheets-excel-xml/
And Ive incorporated it in my site as follows
$dbase->loadextraClass('excel.xml');
$excel = new excel_xml();
$header_style = array(
'bold' => 1,
'size' => '14',
'color' => '#000000',
'bgcolor' => '#ffffff'
);
$excel->add_style('header',$header_style);
if(isset($_POST['fec_save']))
{
if($_POST['reporttype']=='films')
{
$films = $dbase->runquery("SELECT datetime,title,country_of_origin,language,runningtime,(SELECT name FROM fec_client WHERE filmid = fec_film.filmid) AS client, (SELECT rating_decision FROM fec_rating_report WHERE filmid = fec_film.filmid) AS rating FROM fec_film WHERE datetime >= '".strtotime($_POST['fromdate'])."' AND datetime <= '".strtotime($_POST['todate'])."'",'multiple');
$filmcount = $dbase->getcount($films);
//continue with excel buildup
$columns = array('Date','Title','Origin','Language','Minutes','Client','Rating');
$excel->add_row($columns,'header');
for($i=1; $i<=$filmcount; $i++)
{
$film = $dbase->fetcharray($films);
$excel->add_row($film['datetime'],$film['title'],$film['country_of_origin'],$film['language'],$film['runningtime'],$film['client'],$film['rating']);
}
$excel->create_worksheet('From_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
$xml = $excel->generate();
$excel->download('FilmsClassified_from_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
}
}
I would like some assistance as to what I maybe doing wrong.
Thanks
Too long to post as a comment:
$xml = $excel->generate();
creates all the xml file content as a string and stores it in $xml
while
$excel->create_worksheet('From_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
creates the xml and directs it to output, with appropriate headers for downloading.
So you're not using the class correctly, as that's unnecessary duplication of work.

Save ini file with comments

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]\n";
foreach($values as $key => $val){
if(is_array($val)){
foreach($val as $k =>$v){
$tmp .= "{$key}[$k] = \"$v\"\n";
}
}
else
$tmp .= "$key = \"$val\"\n";
}
$tmp .= "\n";
}
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.

Categories