Storing settings, to edit later, in PHP - php

I am writing a PHP application that will have the ability to edit settings through a web interface. I didn't mean for the user (and actually, it will only be admins) to be able to load the file up in a text editor, but rather, they make a change using a form, and that will change the settings file (and do other things as well).
At this stage in the development, settings are stored in a PHP file, for example:
define ('UPLOAD_DIR','uploads/');
define ('DISPLAY_NUM',true);
$names = array('a' => 'b','c'=>'d','e'=>'f');
However, parsing arrays (and they get more complicated (i.e multilevel nested) than the above), doesn't seem so fun. And because specific settings can be added and removed, reading the entire file, and then writing out all the settings again, doesn't seem fun either.
What are the advantages and disadvantages to using the following formats? (And any others that I missed out):
Custom XML
INI (able to use parse_ini_file)
(Using a database is not suitable due to the requirements for the project. I understand in many situations a database would be prefered, just not in this case.)
If you were unable to use a database, and had to store settings that could be edited using a web interface, what would you do?
(Note: This is a different question to this one, where settings can't be changed, it's PHP file all the way. And yes, the setup does currently write out a PHP file with the correct settings.)

If you're not committed to using XML, you may like to consider YAML. I've only used it with Ruby, but a quick Google suggests there are a few options for PHP support. TBF, the links there include some arguments against using YAML with PHP, but YMMV.

OK, I didn't get any sort of answer I was looking for. Here's the sort of thing I was expecting.
INI
Storing settings in an INI file might be appropriate for simple settings which you want the user to edit by hand.
However, creating complex arrays is not easy, and would require some mental acrobatics to understand which heading is at which level of the array.
Reserved words, which must not be used anywhere in the file, include: yes, no, true, and false, this might be problematic.
Constants can be used in the file.
No built in method of writing out INI files.
XML
Can use the SimpleXML Extension, which "provides a very simple and easily usable toolset" to turn XML into an object that can then be processed using the normal methods.
Allows the use of very complex arrays.
Possible to edit by hand, if required.
Can use external tools to verify the validity of the file.
Many many XML processors available for PHP.
YAML
http://yaml.org/
http://www.techyouruniverse.com/software/dont-use-yaml-for-php-use-parse%5Fini%5Ffile
Remember: no database. Requires being able to use complex arrays.

I wouldn't like the idea of someone having direct access over settings, so it's important to provide an interface to act as a buffer, preventing deliberate attacks and ensuring clean output.
With that in mind the choice of server side format is not important at all, as long as you can interface with it correctly all other problems can be worked around.

I'd recommend a custom XML file, that way your config will scale well and you can use PHP XML libraries to access it.
A quick example:
<myconfig>
<define>
<name>UPLOAD_DIR</name>
<value>uploads/</value>
</define>
<define>
<name>DISPLAY_NUM</name>
<value>true</value>
</define>
<array id="names">
<value index="a">b</value>
<value index="c">d</value>
<value index="e">f</value>
</array>
</myconfig>

PHP has built in functions for editing and parsing INI files, which use a plain-text format to store program settings.
http://us.php.net/manual/en/function.parse-ini-file.php
http://us.php.net/manual/en/function.parse-ini-string.php

I have used a two step approach. The variables and their names are stored in the database with an interface that gives the user the ability to change them. When they change them a file gets saved onto the server and then referenced throught out the application (The changes are alos saved back to the DB). Makes updating easy and makes backups simple - no need to backup the files, just backup the database. The resulting files are just .inc files that are in the format $variableName = 'variablevalue';

And why not plain php?
configure-form.php
form method=POST action='configure.php',
input fields ex. name='upload' value='<?php echo UPLOAD; ?>'
a configure.php file:
$myfile = 'sets.php';
$fh = fopen( $myfile, 'w' );
$upload = '"/upload/"';
$txt = "define( UPLOAD, '" . $_POST['upload'] . "' );";
fwrite( $fh, $txt );
fclose( $fh );
and there you have it. Simple php which creates configure file for you.

Related

How to make a CMS config file in PHP (custom)

I am making a custom CMS in PHP and I want to know what the best way would be to create a config file for it. I want it where I can change the variables from within the admin panel I am going to add. I have not messed with the filesystem functions before or any other file functions so I am not sure what would be the best approach.
Thanks!
An .ini file can be structured quite well and you'll be able to update just sections of. Compared to a straight PHP configuration it can be edited with an easier syntax.
To parse the .ini file into a PHP array, use the function parse_ini_file()
If you want a human-readable config file format then look into parse_ini_file(). You'll need to be able to write to the file too, see: create ini file, write values in PHP.
There's a PEAR Package Config_Lite that seems like it should work too.
If readability doesn't matter then save it to a database.
If you want the variables to be changeable via an admin web interface, store those variables in the database like any other CRUD data.
The best idea I think is to use MySQL to store the data.
However, if you cannot do that for some reasons, then I would suggest to make it an XML file and then you can get variables from SimpleXML, and such, you can view all and put their values to a form. Then, the destination PHP could easily make a string like "<val1>".$_POST["value1"]."</val1><val2>".$_POST["value2"]."</val2>". Finally, it would save the file through simple file system functions, which you can learn with googling "php file write".
Or another idea is the parse_ini_file() which is already mentioned.
If you don't understand something, ask. Or Google!

Determine scripting language from string

I've written a generic file system viewer in php and I'd like to add context highlighting. Geshi looks good for this, but appears to require me to send in the language I want to highlight the code in.
Any existing methods on how to determine the scripting language of a given file by contents and/or location?
I have the mime type from:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = #finfo_file($finfo, $full_path );
That lets me know it's text at least (I allow download of non text too).
I'm thinking that parsing the bang line/file extension or looking for simple tags like php would get me a good chunk of the way for things like perl/shell scripts/php.
I also have the path to the file, as these files are coming directly off the source servers so path based rules may work for things like /etc/httpd/conf.d/*, /etc/passwd.
Perfect accuracy isn't really a problem as I'll allow the user to override the language used for the syntax. I just want to provide a low overhead educated guess to start with without writing this from scratch.
One other caveat. Some of these files can be > 150mb so I'd like to only read part of the file although I could just turn off this feature for large files if needed.
If you can call out to an external program, try the Linux file command.
I'm surprised noone pointed me to prettify.js from google code. It will probably do everything I need it to, client side.

Storing Configuration without MySQL

I want to be able to store website configuration without the use of mysql. I also want the user to be able to change this information from a web page. What's the best methods to do so?
Valuable options are a SQLite database, or just a PHP file containing a serialized array if you want a really simple option:
// reading configuration
$config = unserialize(file_get_contents('config'));
// storing configuration
file_put_contents('config', serialize($config));
Storing a file is the easiest option. You could store it in plain text, XML, JSON, etc. You might want to try an ini file which can be read/written by PHP - in which case this answer should help.
I would use a .ini file format to store configuration. It's human readable in its raw format and fairly easy to parse via PHP (parse_ini_file). A point to note here is that PHP (strangely) doesn't support writing to ini files natively, but if you look at the manual page for parse_ini_file you can find an user submitted example of how do it.
Altough I have not used in PHP projects, YAML (Yet Another Markup Language) seems like a good format to store configuration info (it's pretty much the default config format for rails projects). You can use the syck pecl library to easily read and write stuff in the YAML format
You could try cloud based databases if you don't have access to store data on your own server.

Editing files in PHP

Is there a way to append or remove a line of text from a file using PHP.
I am in the process of writing a hosting control panel for my specific web hosting stack and would like to be able to make changes to the files with minimal requirements to touch the file system, and as such would like not to have to rewrite the whole file to add or remove a configuration option.
There is no way to remove a line from a file without first parsing the file into lines and then writing it out again.
You can append to a file by using fopen with the $mode set to 'a'
$fp = fopen('myfile', 'a');
For appending, you should use fopen with the $mode of a.
See this please, on how to delete a line from the file.
Yes, you can open files in append mode:
$fh = fopen('testFile.txt', 'a');
If you now write to the file, the new content gets appended.
See fopen and from this documentation:
'a': Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
Removing the last line is not possible though.
Working with files in PHP is full of pitfalls, particularly wrt concurrency and locking. The fact that you are writing config files implies also that you are exposing tasks normally only available to a user with root privileges over the web. You did not mention these things in your post, but your question is trivial in comparison to addressing these issues.
Regarding your question - although its fairly trivial to implement what you propose (e.g. by exec'ing sed - although you did not did say what OS this is running on) I'd recommend creating a copy of the original file in some other representation - obvious candidates would be a database - where you can apply sequence numbers to the lines and easily create a gap to populate, or a PHP SplDoublyLinkedList stored in the session. Then once the user has effected as many changes as they require, regenerate the file in a single operation from the working representation.
Note that, ultimately, regardless of how you implement the solution the solution will rewrite the entire file - its just a question of how much of this process is exposed within your code.
Bear in mind, that what you are doing is just the same as most php web scripts - except while they manipulate and reqrite HTML, you're doing it with a different file type - so you might want to look at how other PHP templating systems are written, and consider whether you can create a template for your config files.
HTH
C.
If you need to change something in the middle of the file, you have to read it, parse it and save it back. Othwerwise you can only append something to the end of it.
You should not be concerned about the cost of this operation though, as it's a configuration file that won't likely be changed a hundred times every second, it should take negligible time.
If you want more flexibility in access/update/delete I think you should consider moving your configuration file to a database table.

A design suggestion for changing php or general server side code through a web console

Ok so this is my situation...a web application in PHP uses a "config" file for various parameters. This config file is nothing but a php file, say config.php with a global array of the form
$config['param_name'] = 'param_value';
$config['param_name2'] = 'param_value2';
Now I am currently writing an admin app that I want to use to control the main app. One of the things I want the admin app to be able to do is change the config values. So my use case will be something like change the value through an html form element and it should change the config.php replacing the value of the corresponding array index.
This is obviously not specific to php; but I'd love to hear some ideas on how one would go about editing this file. Any ideas?
Thanks!
I have another suggestion: have the configuration parameters sit in a database. Have your admin console work on the database instead.
If you are worried about performance, use APC to cache the parameters.
This way, you can add this configuration database to your other database backup procedure you have already in place.
I would suggest moving all configurable options out of the PHP file and into an external storage (INI file, database, xml, anything). Then you can initialize all the variables you read from the external file in your application's bootstrap file
Another option is to modify the PHP configuration file so it reads its information from an easy-to-access format like YAML.
That way the config file could be accessed by just about any language. A good alternative if you don't want yo use a database.

Categories