FuelPHP update of ORM results in " instead of " sporadically - php

I'm using PHP 5.4.4 and I'm getting very strange behavior with the FuelPHP ORM save and update functions.
I'm trying to save either serialized or JSON data to a field in the database so something like {"name":"michael"}. When I use the model->save() directly after Model::forge() it seems to work fine 100% of the time and the string you see is the one that gets stored in the MySQL db.
However, if I immediately change something like model->property = 'new property' (not the JSON or serialized data property) and then do another model->save() it will 90% of the time turn all my " into "
It seems that when I debug the issue and step through line by line, it will not reproduce this problem! It will make through the entire script and still have the correct " instead of "
This problem is driving me nuts. I would assume its a configuration thing or there would be a lot more complaints, but I can't find the right switch. I've set both
php_flag magic_quotes_gpc Off and php_flag magic_quotes_runtime Off in my .htaccess (although it shouldn't be needed in PHP 5.4+) and verified that both are false.
I'm out of ideas here. Anything to investigate would be really helpful.

Your ORM maybe using some sort of escape function to save your json string. This is a security feature to prevent sql injection attacks. Use a noSql solutions like MongoDB or CouchDB if you need to store json. Otherwise you'll need to cleanup your json strings after they come out of mysql and before you decode them.
http://dev.mysql.com/doc/refman/5.0/en/string-literals.html

Try adding some "echo" statements to print out your variables so that you can figure out where its happening. That usually goes a long way toward finding out why.
You might also try adding something like double_encode for the html entities to stop it from encoding them.

if " are converted to " in database then its not a problem. Its for security. If you render the output on browser it will come up as " again.
And if its your browser displaying " as " then you need to decode the value before printing .

Related

Defining vars for database

I have worked with MySQL before but it has been a LONG time ago. Now I am trying to set up a database using phpMyAdmin.
I am trying to setup this database for the Article Friendly script. The instructions state that you need to use a little script that they have furnished:
define("DB_NAME","a6852953_article");
define("SERVER_NAME","'mysql12.000webhost.com'");
define("USER_NAME","a6852953_article");
define("PASSWORD","*********");
$dbhost=SERVER_NAME;
$dbuser=USER_NAME;
$dbpasswd=PASSWORD;
$dbname=DB_NAME;
It chokes on the first line, and if I remove that it chokes on whatever is there.
The syntax looks correct to me with what little I remember and I also checked the manual for 5.1 which is what my host uses.
Can anyone spot anything wrong?
Looks like it might actually be choking on the second line...
define("SERVER_NAME","'mysql12.000webhost.com'");
... likely because you have single quotes inside the double quotes. Try changing the line to this:
define("SERVER_NAME","mysql12.000webhost.com");
If it is the first line however, make sure that the database you listed already exists -- if not, you should be able to login to phpMyAdmin and run:
CREATE DATABASE a6852953_article
:)

Using PHP to replace a line in a flat-file database

There are quite a few different threads about this similar topic, yet I have not been able to fully comprehend a solution to my problem.
What I'd like to do is quite simple, I have a flat-file db, with data stored like this -
$username:$worldLocation:$resources
The issue is I would like to have a submit data html page that would update this line based upon a search of the term using php
search db for - $worldLocation
if $worldLocation found
replace entire line with $username:$worldLocation:$updatedResources
I know there should be a fairly easy way to get this done but I am unable to figure it out at the moment, I will keep trying as this post is up but if you know a way that I could use I would greatly appreciate the help.
Thank you
I always loved c, and functions that came into php from c.
Check out fscanf and fprintf.
These will make your life easier while reading writing in a format. Like say:
$filehandle = fopen("file.txt", "c");
while($values = fscanf($filehandle, "%s\t%s\t%s\n")){
list($a, $b, $c) = $values;
// do something with a,b,c
}
Also, there is no performance workaround for avoiding reading the entire file into memory -> changing one line -> writing the entire file. You have to do it.
This is as efficient as you can get. Because you most probably using native c code since I read some where that php just wraps c's functions in these cases.
You like the hard way so be it....
Make each line the same length. Add space, tab, capital X etc to fill in the blanks
When you want to replace the line, find it and as each line is of a fixed length you can replace it.
For speed and less hassle use a database (even SQLLite)
If you're committed to the flat file, the simplest thing is iterating through each line, writing a new file & changing the one that matches.
Yeah, it sucks.
I'd strongly recommend switching over to a 'proper' database. If you're concerned about resources or the complexity of running a server, you can look into SQLite or Berkeley DB. Both of these use a database that is 'just a file', removing the issue of installing and maintaining a DB server, but still you the ability to quickly & easily search, replace and delete individual records. If you still need the flat file for some other reason, you can easily write some import/export routines.
Another interesting possibility, if you want to be creative, would be to look at your filesystem as a database. Give each user a directory. In each directory, have a file for locations. In each file, update the resources. This means that, to insert a row, you just write to a new file. To update a file, you just rewrite a single file. Deleting a user is just nuking a directory. Sure, there's a bit more overhead in slurping the whole thing into memory.
Other ways of solving the problem might be to make your flat-file write-only, since appending to the end of a file is a trivial operation. You then create a second file that lists "dead" line numbers that should be ignored when reading the flat file. Similarly, you could easily "X" out the existing lines (which, again, is far easier than trying to update lines in a file that might not be the same length) and append your new data to the end.
Those second two ideas aren't really meant to be practical solutions as much as they are to show you that there's always more than one way to solve a problem.
ok.... after a few hours work..this example woorked fine for me...
I intended to code an editing tool...and use it for password update..and it did the
trick!
Not only does this page send and email to user (sorry...address harcoded to avoid
posting aditional code) with new password...but it also edits entry for thew user
and re-writes all file info in new file...
when done, it obviously swaps filenames, storing old file as usuarios_old.txt.
grab the code here (sorry stackoverflow got VERY picky about code posting)
https://www.iot-argentina.xyz/edit_flat_databse.txt
Is that what you are location for :
update `field` from `table` set `field to replace` = '$username:$worldlocation:$updatesResources' where `field` = '$worldLocation';

How to capture unset REQUEST values in PHP

I'm really unsure if this is even possible but we have an issue where we control an interface that is having XML posted in to it via HTTP post in the form of www.url.com/script.php?xml=<xmlgoeshere>. That is then URL encoded and passed in to us, and we decode and parse it.
Except I have one client who just refuses to url encode their incoming code, which works fine except for when the XML hits an ampersand, at which point everything is being parsed as an end of the xml variable.
www.url.com/script.php?xml=<xmlstart...foo&bar.../>
The end result being that I have XML being POST/GET'd into the xml variable as normal, and then I lose half of the incoming content because of the ampersand.
Now I know that's expected/proper behavior, my question is, is it possible to capture the &bar.../> segment of this code, so that if we hit a known error I can crowbar this into working anyways? I know this is non-ideal but I'm at my wit's end dealing with the outside party.
UPDATE
Ok so I was totally confused. After grabbing the server variables as mentioned below, it looks like I'm not getting the querystring, but that's because on the query they're submitting it has:
[CONTENT_TYPE] => application/x-www-form-urlencoded
[QUERY_STRING] =>
That being the case, is the above behavior still to be expected? Is their a way to get the raw form input in this case? Thanks to the below posters for their help
You'd be hard pressed to do it, if it's even possible, because the fragments of a query string take the format foo=bar with the & character acting as the separator. This means that you'd get an unpredictible $_GET variable created that would take the key name of everything between the & and the next = (assuming there even is one) that would take the value from the = to the next & or the end of the string.
It might be possible to attempt to parse the $_GET array in some way to recover the lost meaning but it would never be all that reliable. You might have more luck trying to parse $_SERVER ['QUERY_STRING'], but that's not guaranteed to succeed either, and would be a hell of a lot of effort for a problem that can be avoided just by the client using the API properly.
And for me, that's the main point. If your client refuses to use your API in the way you tell them to use it, then it's ultimately their problem if it doesn't work, not yours. Of course you should accommodate your clients to a reasonable standard, but that doesn't mean bending over backwards for them just because they refuse to accommodate your needs or technical standards that have been laid down for the good of everyone.
If the only parameter you use is xml=, and it's always at the front, and there are no other parameters, you can do something like this pseudocode:
if (count($_GET)>1 or is_not_well_formed_xml($_GET['xml'])) {
$xml = substr($_SERVER['QUERY_STRING'], 4);
if (is_not_well_formed_xml($xml)) {
really_fail();
}
}
However, you should tell the client to fix their code, especially since it's so easy for them to comply with the standard! You might still get trouble if the xml contains a ? or a #, since php or the web server may get confused about where the query string starts (messing up your $_SERVER['QUERY_STRING'], and either PHP, the client's code or an intermediary proxy or web server may get confused about the #, because that usually is the beginning of a fragment.
E.g., Something like this might be impossible to transmit reliably in a query parameter:
<root><link href="http://example.org/?querystring#fragment"/></root>
So tell them to fix their code. It's almost certainly incredibly easy for them to do so!
UPDATE
There's some confusion about whether this is a GET or POST. If they send a POST with x-www-form-urlencoded body, you can substitute file_get_contents('php://input') for $_SERVER['QUERY_STRING'] in the code above.
YES, Its possible. Using $_SERVER["QUERY_STRING"].
For your url www.url.com/script.php?xml=<xmlstart...foo&bar.../>, $_SERVER["QUERY_STRING"] should contain, xml=<xmlstart...foo&bar.../>;
The following code should extract the xml data.
$pos=strpos($_SERVER["QUERY_STRING"], 'xml');
$xml="";
if($pos!==false){
$xml = substr($_SERVER["QUERY_STRING"], $pos+strlen("xml="));
}
The problem here is that the query string will be parsed for & and = characters. If you know where your = character will be after the "bar" key then you may be able to capture the value of the rest of the string. However if you hit more & you are going to need to know the full content of the incoming message body. If you do then you should be able to get the rest of the content.

php source related question

i have some php source it can send form data info to other page under mysql 4.x version.
but after upgraded to mysql 5.x version, this php source can't send form data info to other page.
i was searched many info, but don't have idea what's wrong with my php source.
i just can guess this is related with mysql upgrade and i have to edit my php source,
but lack of knowledge it very tough for me.
if anyone help me or give some hint it really appreciate!
my php source is consist of 3 part.
form sender page ( http://pastebin.com/3Sg7SyWV )
-> submited form data info checking page ( http://pastebin.com/WEx5tEn2 )
-> insert form data to DB ( http://pastebin.com/918iZkgw )
for several day i was search and search but lack of my knowledge about php and mysql
it very hard to resolve.
Thanks in advance
You're not checking if your insert query succeeds. I can't tell which MySQL library you're using, but generally they all return FALSE if a query fails, so you could change your query line to something like:
$DB->ExecSql($InsertQuery) or die($DB->whatever_returns_error_information());
If something's wrong with the query, then this would abort the script and output any error information produced.
As well, it doesn't look like you're escaping your query data anywhere. That leaves you wide open to SQL injection. And as well, any of the form data which contains even a single quote (') will "break" the query by introducing syntax errors. If you had proper error checking in there, you'd have gotten a syntax error report.
For that matter, where are you extracting the submitted data and building all those variables you paste into the query? There's only one place in your three scripts where $_POST is referred to, and it seems to be in an error output function which simply dumps out each key/value as hidden form fields (and in there you're also not escaping/quoting the data, so your form itself is vulnerable to XSS attacks).

How can I store PHP code inside of a mysql table

I am working on building a small php/mysql script that will act something like a wordpress blog but will just be a small site for my eyes only to store PHP code snippets. So I will have categories and then pages with sample code that I write with a javascript syntax highlighter. Instead of storing my php code snippets in the file I am wanting to save them to mysql DB. So what is the best way to save PHP into mysql and to get it out of mysql to show on the page?
My end result will be something like this
alt text http://img2.pict.com/c1/c4/69/2516419/0/800/screenshot2b193.png
Update:
I just wasn't sure if I needed to do something special to the code before sending it to mysql since it has all different kinds of characters in it
Just store in a text field, as is. Not much more beyond that.
If you're not using some kind of database abstraction layer, just call mysql_real_escape_string on the text.
Do you want to be able to search the php code? If so, I recommend using the MyISAM table type as it supports full text indexes (InnoDB does not). Your choices for column type when it comes to a fulltext index are char, varchar and text. I would go with text as your code snippets might get too long for the other types.
Another point worth mentioning, is make sure you properly escape all php code (or any value for that matter) before you insert it. The best way to do this is by using parameterized queries.
Unless I'm missing part of the problem, you should be safe storing it as a TEXT field in a MySQL database. Just make absolutely sure you sanitize the code snippets, as PHP code in particular is quite likely to contain the characters that will escape out of an SQL string. (If you're already using an SQL framework, odds are the framework is doing this for you.)
Store as text (varchar) in the database.
Use cascading style sheet (css) to format code.
http://qbnz.com/highlighter/
Try this:
mysql select ...
eval('?>' . $row['phpcode'] . '<?php ');

Categories