Save ini file with comments - php

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.

Related

How to write a ini file in PHP codeigniter?

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).

How to get a piece of text from PHP file

From wp-config.php file I need to get DB name, username, password values without including the wp-config file and assign them to three separate variable for further use.
define('DB_NAME', 'somedb');
define('DB_USER', 'someuser');
define('DB_PASSWORD', 'somepass');
my script will be in the same folder. No I don't want to use any WordPress functions.
If you really don't want to include the file, as mentioned in the comments already,
we can read the file contents into an array with file().
The iterate over each line and apply some cleanup, until we get to a format we can work with:
<?php
$config = file('wp-config.php');
$dbLines = [];
foreach($config as $line){
if (stristr($line,"define('DB_")!==FALSE){
$dbLines[] = $line;
}
}
array_walk($dbLines, 'cleanup');
// apply the cleanup() function to all members of the array, basically to each line
function cleanup(&$value){
// replace the leading 'define(' and trailing closing bracket
$value = str_replace(
array("define(",");"),'',$value
);
$value = preg_replace('#\s+//(.*)#','',$value); // remove the comments
}
// at this point we have a csv structure with a single quote as the delimiter
// comma+space as a separator
$dbConfig = [];
foreach ($dbLines as $dbline){
// read the line into separate variables and build an array
list($key,$value) = (str_getcsv($dbline,', ',"'"));
$dbConfig[$key] = $value;
}
print_r($dbConfig);
This will output
Array
(
[DB_NAME] => putyourdbnamehere
[DB_USER] => usernamehere
[DB_PASSWORD] => yourpasswordhere
[DB_HOST] => localhost
[DB_CHARSET] => utf8
[DB_COLLATE] =>
)
If you want to access a single element from the array, just
print $dbConfig['DB_HOST'];

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

How to save php config?

I have a standard config file: $variable = 'value';, but at the last moment came up to use the web interface to configure it. So what is the best way to read the file, find the value of variables and then resave the file again?
At the moment I have 2 ideas:
1) RegExp
2) Keep somewhere array example
Store all config values in an associative array like so:
$config = array(
'variable' => 'value'
);
For the web interface, you can easily loop over the entire array:
foreach($config as $key=>$value) { ... }
After making changes, loop over the array and write it back to the file. (You really should be using a DB for this, though).
When you include the file, you can either use it like this:
include('config.php');
echo $config['variable']
// or
extract($config);
echo $variable;
Note: If you extract, it will overwrite any variables by the same name you might have defined before extracting.
PS - To make it easier to read and write to and from a file, I would just use json encoding to serialize the array.
Use a db
If your config is user defined - it would be better to store the config in a database. Otherwise you have this "novel" problem to solve but also potentially introduce security problems. I.e. for any one user to be able to edit your config files - they must be writeable to the webserver user. That opens the door to injecting malicious code into this file from a web exploit - or simply someone with direct access to your server (shared host?) finding this writeable file and updating it to their liking (e.g. putting "<?php header('Location: my site'); die;" in it).
One config variable
If you must manage it with a config file, include the file to read it, and var_export the variables to write it. That's easiest to do if there is only one config variable, that is an array. e.g.:
function writeConfig($config = array()) {
$arrayAsString = var_export($config, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Allow partial updates
If you are changing only some variables - just include the config file before rewriting it:
function writeConfig($edits = array()) {
require 'config.php';
$edits += $config;
$arrayAsString = var_export($edits, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Multiple config variables
If you have more than one variable in your config file, make use of get defined vars and loop on them to write the file back:
function writeConfig($_name = '', $_value) {
require 'config.php';
$$_name = $_value; // This is a variable variable
unset($_name, $_value);
$string = "<?php\n";
foreach(get_defined_vars() as $name => $value) {
$valueAsString = var_export($value, true);
$string .= "\$$name = $valueAsString;\n";
file_put_contents('config.php', $string);
}
}
The above code makes use of variable variables, to overwrite once of the variables in the config file. Each of these last two examples can easily be adapted to update multiple variables at the same time.

Editing PHP using PHP (admin center)

Am developing an admin center where I can edit configuration files (written in PHP). I do NOT want to store these values in a mySQL table (for various reasons). So say my config.php has contents like:
<?php
$option1 = 1;
$option2 = 2;
$option4 = 5;
$option7 = array('test','a','b',c');
?>
Now say in one of the admin pages I will only be changing a few values like option2 or option4 etc. Any ideas on what would be the best way to go about this.
I know one option is to read the PHP file completely and write parts of it using REGEX. Any way to make this more efficent? I don't want the config.php file to break because of some error on the user's end. Any ideas on how to ensure that it works?
If you have some liberty about the way you store configuration values, you may use ini files.
All you have to do is load the content of the ini file in an array with parse_ini_file, then modify values in that array and finally overwrite the file with new values, as described in this comment.
For obvious security reasons it's a good idea to place those files out of your document root.
sample content of ini file :
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
sample code (using safefilewrite function) :
<?php
$ini_file = '/path/to/file.ini';
$ini_array = parse_ini_file($ini_file);
$ini_array['animal'] = 'CAT';
safefilerewrite($file, implode("\r\n", $ini_array));
?>
var_export() is probably the function you're looking for.
You can write/read the settings to a file using the following code:
$content = array();
//fill your array with settings;
$fh = fopen ( $bashfile, 'w' ) or die ( "can't open file" );
fwrite ( $fh, $content );
fclose ( $fh );
to read it you use:
file_get_contents() //this will return a string value
OR
Line by line:
$lines = file('file.txt');
//loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
print "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

Categories