When I send json data from action script 3 to php using URLVariables, the json string changes and cannot be used as json inside php. How to prevent this happening? Or how to fix it?
trace from Flash(send moethod POST, variable name myObject):
[{"data1":"value1","data2":"value2",...},{...},...]
echo $_POST['myObject'] from PHP:
[{\"data1\":\"value1\",\"data2\":\"value2\",...},{...},...]
echo json_decode($_POST['myObject']) from PHP is nothing, when var_dump(json_decode($_POST['myObject']):
NULL
The server automatically escape the POST data (As I remember it is an option in php.ini).
To unescape , use stripslashes function, and after decode your string ;)
json_decode(stripslashes($_POST['myObject']));
Based on #therefromhere 's comment, a better solution to set magic_quotes_gpc off.
You can do this if you have a root access for the server, or you have permission to set php flags at runtime.
Here is some help for this:
http://php.net/manual/en/security.magicquotes.disabling.php
Based on #nl-x 's comment if you want to solve this problem, undepended from your server configuration:
$myObject = get_magic_quotes_gpc() ? //Examine: is magic quotes gpc on?
stripslashes($_POST['myObject']) : //if true: unescape the string
$_POST['myObject']; //if false, do nothing
json_decode($myObject);
//When php 5.3 or earlier installed on server
Related
I have a string created by recipeBlob = JSON.stringify(recipeData). It is a long string but here is a sample of it:
"properties":{"Energy":{"val":90.6,"unit":"cal","rdi":"2000"},"Protein":{"val":0.4,"unit":"g","rdi":"50.00000000"},"Fat":{"val":0.6,"unit":"g","rdi":"65.000000000"},"Carbohydrates":{"val":23.3,"unit":"g","rdi":"300.0000000"},"Dietary Fiber":{"val":4.1,"unit":"g","rdi":"25"},"Sugars":{"val":18.8,"unit":"g","rdi":null}
which I send via $.post like this:
$.post('scripts/save_blob.php', {
blob : recipeBlob
});
The $string = $_POST['blob'] that arrives at my PHP script is showing up like this:
{\"properties\":{\"Energy\":{\"val\":90.6,\"unit\":\"cal\",\"rdi\":\"2000\"},\"Protein\":{\"val\":0.4,\"unit\":\"g\",\"rdi\":\"50.00000000\"},\"Fat\":{\"val\":0.6,\"unit\":\"g\",\"rdi\":\"65.000000000\"},\"Carbohydrates\":{\"val\":23.3,\"unit\":\"g\",\"rdi\":\"300.0000000\"}
When I run json_decode($string) it is returning error #4 which is json syntax error.
I don't know at which part of the process the characters are being escaped, which I need to avoid.
#Juhana provided the most direct answer to the question, PHP magic quotes were turned on on the server, thus automatically escaping quotes.
#dfsq provided the solution I actually used, which is to just send the javascript object without stringifying it. it arrives to the PHP script as an array.
I'm writing PHP code that uses a database. To do so, I use an array as a hash-map.
Every time content is added or removed from my DB, I save it to file.
I'm forced by my DB structure to use this method and can't use mysql or any other standard DB (School project, so structure stays as is).
I built two functions:
function saveDB($db){
$json_db = json_encode($db);
file_put_contents("wordsDB.json", $json_db);
} // saveDB
function loadDB(){
$json_db = file_get_contents("wordsDB.json");
return json_decode($json_db, true);
} // loadDB
When echo-ing the string I get after the encoding or after loading from file, I get a valid json (Tested it on a json viewer) Whenever I try to decode the string using json_decode(), I get null (Tested it with var_dump()).
The json string itself is very long (~200,000 characters, and that's just for testing).
I tried the following:
Replacing single/double-quotes with double/single-quotes (Without any backslashes, with one backslash and three backslashes. And any combination I could think of with a different number of backslashes in the original and replaced string), both manually and using str_replace().
Adding quotes before and after the json string.
Changing the page's encoding.
Decoding without saving to file (Right after encoding).
Checked for slashes and backslashes. None to be found.
Tried addslashes().
Tried using various "Escape String" variants.
json_last_error() doesn't work. I get no error number (Get null, not 0).
It's not my server, so I'm not sure what PHP version is used, and I can't upgrade/downgrade/install anything.
I believe the size has something to do with it, because small strings seem to work fine.
Thanks Everybody :)
In your JSON file change null to "null" and it will solve the problem.
Check if your file is UTF8 encoded. json_decode works with UTF8 encoded data only.
EDIT:
After I saw uploaded JSON data, I did some digging and found that there are 'null' key. Search for:
"exceeding":{"S01E01.html":{"2217":1}},null:{"S01E01.html":
Change that null to be valid property name and json_decode will do the job.
I had a similar problem last week. my json was valid according to jsonlint.com.
My json string contained a # and a & and those two made json_decode fail and return null.
by using var_dump(json_decode($myvar)) which stops right where it fails I managed to figure out where the problem was coming from.
I suggest var_dumping and using find dunction to look for these king of characters.
Just on the off chance.. and more for anyone hitting this thread rather than the OP's issue...I missed the following, someone had htmlentities($json) way above me in the call stack. Just ensure you haven't been bitten by the same and check the html source.
Kickself #124
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why are escape characters being added to the value of the hidden input
So, I have a file called Save.php.
It takes two things: a file, and the new contents.
You use it by sending a request like '/Resources/Save.php?file=/Resources/Data.json&contents={"Hey":"There"}'.
..but of course, encoding the url. :) I left it all unencoded for simplicity and readability.
The file works, but instead of the contents being..
{"Hey":"There"}
..I find..
{\"Hey\":\"There\"}
..which of course throws an error when trying to use JSON.parse when getting the JSON file later through XHR.
To save the contents, I just use..
file_put_contents($url, $contents);
What can I do to get rid of the backslashes?
Turn magic_quotes off in PHP.ini.
Looks like you have magic_quotes turned on.
If that is the case, either turn it off - Or use a runtime disabling function
Try this:
file_put_contents($url, stripslashes($contents));
you probably have magic quotes enabled, only two things you can do. disable magic quotes in your php.ini or call stripslashes() on $_GET and $_POST globals.
FYI, use $_GET['contents'] as opposed to $contents; newer versions of php will not create the $contents var.
You should disable magic_quotes in your php.ini configuration file. However if this is not possible you can also use the stripslashes() function to get rid of the automatic escaping.
If you can not get magic quotes switched off for your server, then you need to check if it is switched on using get_magic_quotes_gpc() and if it is true, stripslashes().
im letting my users type in texts, then take them to server side php and process them, and if everything goes as it should, i just append the text with jquery without the page having to load all over again.
This is the procedure:
$post_text = htmlspecialchars(mysql_real_escape_string($_POST['post_text']));
some logic...
everything ok!
stripslashes(str_replace("\\n", "", $post_text))
and then i send all the nessesary data witj json
echo json_encode($return);
on the client side i append the html chunk saved in a variable from the server side.
this seems to work on localhost, it removes all the slashes and so on, but online it just doenst remove the slashes, and they keep coming up, when i hit refresh they dissapear becouse then its a
stripslashes($comment['statusmsg_text'])
written out with php straight from the database. Is it the json that adds some extra stuff? i dont get it becouse it works perfectly on localhost.
best of regards,
alexander
The additional slashes might be magic quotes. You shouldn’t rely on them and disable them.
Additionally, mysql_real_escape_string should only be used to prepare strings to be put into a string context in an MySQL statement. Similar applies to htmlspecialchars that should only be used for sanitizing data to be put into an HTML context.
It may be, that on your server and your localhost the magic_quotes_gpc directive is set differently, so your string is double encoded on server side.
Try it without stripslashes, json_encode should handle that. All you need to do is use mysql_real_escape once, before your string touches your database.
I send this string in a GET request
{"foo":[{"bo1":"*","bob":"*"}]}
but get it in PHP as
{\"foo\":[{\"bo1\":\"*\",\"bob\":"\*\"}]}
How do I get it as {"foo":[{"bo1":"*","bob":"*"}]} sending it as part of a query string (or how do I send it via GET method to get it properly)? (Note: I cannot clean it as I have no control over server side.)
Disable magic_quotes: it's deprecated. If you can't, you can always use stripslashes on the input:
$goodStr = stripslashes($_GET['badStr']);
Your php config have enabled magic_quotes_gpc, which causes automatic escaping of quotes and double quotes in all _GET, _POST, and _COOKIE superglobals.
If you do not need it, turn it off. If you do, then you should probably rewrite the code which relies on this behaviour, as it is depreciated, and will be removed in future verions of php.
You should turn it of in php.ini if possible.
Anyway, if you, for some reasons, cannot turn off this just use stripslashes($your_json);
If the server runs on Apache, create a file called .htaccess in the site root (the leading period is part of the filename). Put the following code in the file:
php_flag magic_quotes_gpc Off
Otherwise, you'll need to use stripslashes() every time.