Im creating a picture viewer for a friend of mine but i am unable to use a database because his hosting doesn't allow one.
So im left trying to use ini files but i dont know how to write a structured ini file using php..i have successfully put together a script to read it via parse_ini_file() and break it down into it seperate categories and keys but i need to know how to write the acctuall structure if there isn't one already.
For example
[flowerpics]
picone = filelocation
pictwo = filelocation
[artpics]
picone = filelocation
this is how im basing my parse_ini_file() script for ...so what if he wants to add a whole new category to this file ..lets say he wants to add "Rockandrollpics" ...how can i go about adding that into an ini file?
If I were you, I would consider using some standard - like JSON, YAML, or even BJSON - it's almost as simple as INI files, but gives you more control about structuring the data. Your example with JSON:
"flowerpics"
{
"picone" : "filelocation";
"pictwo" : "filelocation";
}
"artpics"
{
"picone" : "filelocation";
}
If you don't use Mysql you can try to use SqlLite instead of.
You needn't anything except php extension sqllite.
Look at http://php.net/manual/en/book.sqlite.php for more info.
Related
I wrote a simple script in plain PHP that uses $_FILES['uploadedfile']['tmp_name'] to fetch a freshly uploaded file and process its contents directly without permanently storing it. The idea is to allow the user to upload a file containing several rows of data that will be automatically parsed and added to a database by the PHP script. There is no need to store the file itself or a reference to it in the database as only the file contents are important. I know of Import CSV to MySQL, but I am trying to keep things clean and easy for the user (and for the time being I am developing with phpDesktop + sqlite so that my application will be portable).
I am now trying to recreate this process within Agile Toolkit but I cannot seem to figure out how. I know that the filestore model must access ['tmp_name'] before it moves/renames the file but I cannot figure out how to poach just this functionality. I tried looking in /lib/Form/Field/Upload.php to see if any of the methods there might be of use, but I am quite new to PHP so these docs are baffling to me. getFilePath() looked promising, but it seems that $_FILES remains empty when I do something like:
$form = $page->add('Form');
$upl = $form->addField('Upload', 'file');
$form->addSubmit();
if ($form->isSubmitted()){
$form->js()->univ()->alert($upl->isUploaded())->execute(); //sends js alert('false')
}
I realize that AJAX cannot be used to post files and I have a feeling this is part of the problem but I am not really sure where to go from here. Any help would sincerely be appreciated.
Thanks.
Agile Toolkit uploads file as soon as it is selected - moves it immediately into filestore and creates database record, so not really what you need.
Anything you write in a plain PHP can also work with Agile Toolkit. You can disable JavaScript in the form by doing this:
$this->add('Form',array('js_widget'=>false));
Such a form would send you a normal POST request.
Ok, I managed to achieve what I wanted by creating a custom extension of Form_Field_Upload and redefining the loadPOST() method within it.
function loadPOST(){
Form_Field::loadPOST();
if($_GET[$this->name.'_upload_action']){
// This is JavaScript upload. We do not want to trigger form submission event
$_POST=array();
}
if($_GET[$this->name.'_upload_action'] || $this->isUploaded()){
if($this->model){
try{
$model=$this->model;
/*Function is identical to parent above this line*/
//process file here and do $model->set('custom_field',$value);
//I am using $this->getFilePath() to analyze the uploaded file
/*Function is identical to parent below this line*/
$model->save();
}catch(Exception $e){
$this->api->logger->logCaughtException($e);
$this->uploadFailed($e->getMessage()); //more user friendly
}
$this->uploadComplete($model->get());
}
}
if($_POST[$this->name.'_token']){
$a=explode(',',$_POST[$this->name.'_token']);$b=array();
foreach($a as $val)if($val)$b[]=$val;
$this->set(join(',',filter_var_array($b,FILTER_VALIDATE_INT)));
}
else $this->set($this->default_value);
}
I sure this is not the most elegant solution but it worked for my purpose anyway.
i have a web site, in where i want to show some strings that may change according to the user lenguage and other parameters. I was thinking in a xml file like:
<strings>
<EN>
<userop1>This is the option 1<userop2>
</EN>
<ES>
<userop1>Esta es la opcion 1<userop1>
</ES>
</strings>
Then, using php something like: echo("You select: ".$userop1);
I really dont know if this is the most inteligent way to strutture the xml, so im asking for suggestiona (please with an example reading script). Thanks for any help!
Why are you using XML, this is an OVER HEAD in performance.
you should use Constants or Arrays.
$lang['en']['title'] = "title";
or separate files for each constants set/language
file: tranlate.en.php
defile('TITLE' , 'title');
since PHP is stateless, every page hit in your app will cause the system to parse this string.
no need for that
I think you shouldn't have all languages in a single xml file - it may get too big, will be harder to maintain, and so. Instead, make a xml for each language.
I am writing a PHP application targeted at non-geeks, non-programmers. I need to create an option page with a bunch of "options" and then store those options...somewhere. Using a database application (MySQL/PostgreSQL/SQLite) is out of the question because it will require more configuration than the user needs to do (I don't want the user to do any kind of configuration if he doesn't want to). So the only solution left is to write the configuration to a configuration file. On the other hand, I also want that configuration file to be human-readable in case the user is a geek and he wants to edit the config file directly (or if he wants to edit the file remotely via SSH or any kind of reason...)
Here are the couple of potential solutions I found:
Using a JSON file...
...Retrieve the data from the file, using json_decode to convert the data, output it into HTML, retrieve any changes, encode back using json_encode, etc. You get the picture. There are a couple things that I don't like about this method, the main one being that the encoded JSON data using PHP will no be well formatted and very hard to edit without being reformatted beforehand.
Using an XML file
I won't describe that solution because I don't really like it either...and I don't know how to use XSLT and don't really want to learn...and because it's a pretty heavyweight solution, at least compared to the JSON solution. Correct me if I'm wrong.
Using an INI file
I love INI files, really I love them! I think they're really the most readable, and it's hard to mess up (ie: syntax errors). The problem with that solution is that there is no native way to write/edit an ini file. I found a topic showing a custom method to write one...that might be the solution I will adopt if I don't find anything better...
Using two files
That last solution seems as reasonable as the INI solution. In fact, I could use an INI file as "input" (the file that the user would edit if he wants to) and an XML/JSON file as output (the file that will be edited by PHP every time the user changes options using the web front-end). At this point, the best solution would be to ask the user to reload the configuration manually if he edited the config file directly, so that the "output" file is always up to date.
I know none of the solutions above are perfect, and that's why I created this topic to ask for advice. What is the best solution? Maybe (probably) I missed yet another solution.
One last thing: YAML isn't a valid solution because it's a lot easier to mess up the syntax if you're not used to it. PHP is not a solution either because editing PHP with PHP is a pain. PHP is only a good solution if I want to retrieve some configuration but not edit it directly via a web front-end.
ini
I'd write ini files, myself. As you said, the syntax is very simple, and that's what you want in a config file. The ini format's "key+value" pairing is exactly what you'd get with a database—without the database.
Related SO you may have seen already: create ini file, write values in PHP
Plus you can use parse_ini_file() to read it.
XML
XML isn't all that bad. It may be more work to write it (and may not be as clear to the user as an ini file), but reading it is really easy.
Create it:
<?php
// Create file
$xml = new SimpleXMLElement( '<?xml version="1.0" ?><config></config>' );
// Add stuff to it
$xml->addChild( 'option1' );
$xml->option1->addAttribute( 'first_name', 'billy' );
$xml->option1->addAttribute( 'middle_name', 'bob' );
$xml->option1->addAttribute( 'last_name', 'thornton' );
$xml->addChild( 'option2' );
$xml->option2->addAttribute( 'fav_dessert', 'cookies' );
// Save
$xml->asXML( 'config.xml' );
?>
Read it:
<?php
// Load
$config = new SimpleXMLElement( file_get_contents( 'config.xml' ) );
// Grab parts of option1
foreach( $config->option1->attributes() as $var )
{
echo $var.' ';
}
// Grab option2
echo 'likes '.$config->option2['fav_dessert'];
?>
Which gives you:
billy bob thornton likes cookies
Documentation for SimpleXML
SimpleXML Docs index
Basic Examples
Details on addChild() and addAttribute(), showing how to generate various XML structures (nested tags vs. attributes, for example)
I'd go with the ini. They're really not that hard to write. I personally hate XML. It's so bloated... even if the file size doesn't matter, it still makes me cringe at it's wordiness and the amount of typing I have to do. Plus, people are dumb. They won't close their tags.
The standard way would be XML files. They don't create that much overhead and are easily extensible. However, JSON files are the easiest on the programming end.
I'd rank my preference:
XML
JSON
ini (last resort)
Unless you have 1000+ options, you really shouldn't worry about the XML file size. The goal here is to keep things easy for the user. This means that whichever method you choose (JSON shouldn't be one of them in my opinion), it should be heavily documented at each config line.
Your two file solution brings me back to the days of sendmail config and makes me shudder.
I would just go with XML, it's self documenting to a point <Email>hi#hi.hi</Email>
Well, you could use PHP's serialize(), and although it is human readable, it isn't the most human readable thing there is. It's on the same level as JSON to implement.
I would like to know how to create a php function that can be installed in php
just like the already built in functions like :
rename
copy
The main point I would like to achieve is a simple php function that can be called from ANY php page on the whole host without needing to have a php function within the php page / needing an include.
so simply I would like to create a function that will work like this :
location();
That without a given input string will output the current location of the file via echo etc
Well, there are a couple of options here. One of them is to actually extend the language by writing an extension. You'd have to muck around with the PHP source code, write it in C, and deal with the Zend Engine internally. You probably wouldn't be able to use this on a shared host and it would be quite time consuming and probably not worth it.
What I would do is put all of your functions into a separate PHP file, say helper_functions.php. Now, go into your php.ini and add the directive: auto_prepend_file = helper_functions.php. This file should be in one of the directories specified in your include_path (that's a php.ini directive too).
What this does is basically automatically put include 'helper_functions.php'; on every script. Each and every request will have these functions included, and you can use them globally.
Read more about auto_append_file.
As others have said, there's probably an easier, better way to do most things. But if you want to write an extension, try these links:
http://docstore.mik.ua/orelly/webprog/php/ch14_01.htm
http://www.tuxradar.com/practicalphp/2/3/0
So you want to extend PHP's core language to create a function called location(), written in C, which could be done in PHP by:
echo __FILE__;
Right. Have fun doing that.
I need to be able to store data for a php application in a file. I need to be able to do this without any sort of external dependencies other than PHP itself.
Here are the requirements I have:
Settings will not be updated/added/removed very often. So updating of settings does not have to be very efficient. However, I do want to be able to do this all through a PHP script, not through editing of files.
Settings will be read constantly, so reading of settings must be very efficient.
Settings are in a unique format, if I had them in an array it might be something like $Settings["Database"]["AccessSettings"]["Username"]["myDBUsername"]; $Settings["Database"]["AccessSettings"]["Password"]["myDBPassword"];
I would prefer to not have settings stored in arrays like I mentioned above. Instead I would prefer some access methods: getConfig("Database","Accesssettings","Username") would return 'myDBUsername'. The reason for this is I want to limit the variables I am storing in the global scope.
What would the best way of getting/retrieving these be?
Do the the hierarchy I was thinking possibly an xml file, but I wasn't sure what PHP was like for accessing xml files (particularly the fact that I need to be able to add, edit, and remove). If it should be XML what sort of xml access should I look into.
If it is another format, I would like some pointers to the right direction for what to look into for how to use that format.
Brian, parse_ini_file is what you need.
Ah, I missed the requirement that you'd be editing this via PHP.
In that case there is nothing native to PHP that you can use for this purpose. You'd have to roll your own.
You could save yourself a ton of time by simply using Zend_Config_Ini though. I know you state that you don't want to use anything else, but Zend Framework is structured to allow you to use whatever pieces of it you need. Zend_Config can be used on it's own. You can certainly just add these few classes to your project and let them handle your INI file parsing.
Here is an example using your samples above:
[config]
Database.AccessSettings.Username = myDBUsername
Database.AccessSettings.Password = myDBPassword
You would load and access this as simply as:
$config = new Zend_Config_Ini('/path/to/ini', 'config');
echo $config->Datbase->AccessSettings->Username; // prints "myDBUsername"
echo $config->Datbase->AccessSettings->Password; // prints "myDBPassword"
To edit and save your config you would use the following:
$config->Database->AccessSettings->Password = "foobar";
$writer = new Zend_Config_Writer_Ini(array('config' => $config,
'filename' => 'config.ini'));
$writer->write();
Edit
Not really sure why people are voting this down based on vog's misguided comments. It is very simple to make this writable by multiple persons by using an exclusive lock. Zend_Config_Writer uses file_put_contents to do it's writing, which has always supported the the LOCK_EX flag, which exclusively locks a file for writing. When using this flag, you cannot have multiple writers attempting to update the file at the same time.
To use this flag with Zend_Config_Writer it's as simple as follows:
$writer = new Zend_Config_Writer_Ini(array('config' => $config,
'filename' => 'config.ini'));
$writer->setExclusiveLock(true);
$writer->write();
An alternate syntax:
$writer = new Zend_Config_Writer_Ini();
$writer->write('config.ini', $config, true); // 3rd parameter is $exclusiveLock
If you're not hand editing, use serialized data.
Writing config using serialize:
file_put_contents('myConfig.txt', serialize($Settings));
Reading config using unserialize:
$Settings = unserialize(file_get_contents('myConfig.txt'));
You could write a class for modifying and getting values for this data using PHP magic functions __get() and __set().
If you are willing to drop in a library, you could use Spyc and have your configuration in a YAML file.
You could also use PHP's support for SQLite which would mean your database is just a file so no need for a DB server.
DBM files may not be a bad idea. PHP has built in support for the various DBM-file varieties:
http://www.php.net/manual/en/book.dba.php