magento escape string for JavaScript part 2 - php

This is a follow up on
magento escape string for javascript
where I accepted #AlanStorm suggestion to use json_encode to escape string literals.
But I now have a new problem with this solution.
when trying to escape a URL that has /'s in it to be rendered as a string literal for JavaScript json_encode seems to add redundant \'s in front of the /'s.
Any new suggestions here?
solutions should take a string variable and return a string that would properly be evaluated to a string literal in JavaScript. (I don't care if its surrounded with single or double quotes - although I prefer single quotes. And it must also support newlines in the string.)
Thanks

some more info: how comes '/');echo
json_encode($v); ?> results in
{"a":"\/"} ?
Details can be found here http://bugs.php.net/bug.php?id=49366
work around for this issue:
str_replace('\\/', '/', $jsonEncoded);
for your issue you can do something like
$jsonDecoded = str_replace(array("\\/", "/'s"), array("/", "/\'s"), $jsonEncoded);
Hope this helps

When I check the JSON format I see that solidi are allowed to be escaped so json_encode is in fact working correctly.
(source: json.org)
The bug link posted by satrun77 even says "It's not incorrect to escape slashes."
If you're adamant to do without and (in this case) are certain to be working with a string you can use a hack like this:
echo '["', addslashes($string), '"]';
Obviously that doesn't help for more complicated structures but as luck has it, you are using Magento which is highly modifiable. Copy lib/Zend/Json/Encoder.php to app/core/local/Zend/Json/Encoder.php (which forms an override) and fix it's _encodeString method.

Related

Put a variable in a string PHP

I am new to Laravel and I am having this question.
I tried out this line of code and it works fine: return redirect("/cards/{$note->id}");
But when ever I try to use the single quotes, it does not work: return redirect('/cards/{$note->id}');
How can I solve this problem ?
What you are doing first is called variable interpolation or string interpolation. You can read more about it here, on PHP docs and here, on Wiki.
It's a feature in PHP that allows you to pass a string and have variables/placeholders inside interpreted.
In your second example you are using single quotes, which does not provide this feature, so you will have to break it up and add the variable manually to the string:
return redirect('/cards/' . $note->id);
If you are interested in a more elaborate explanation and the performance behind it then you can read more on this answer here by Blizz
He concludes that:
Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.
However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.
You should use "/cards/{$note->id}" or '/cards/'.$note->id
The most important feature of double-quoted strings is the fact that variable names will be expanded.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
From PHP documentation
Use it like that:
return redirect('/cards/'. $note->id);
With either single or double quotes

How to deal with Double Quoted String inside a Json object?

So I have a json encoded string by a system, Which for a reason I cannot touch.
See below.
[{"item0":"sometext","item1":"sometext too but i have "quoted string" inside of me"}]
so now my problem is, using json_decode($json_array_above); gives me NULL output as it cannot convert the quoted string...
I try some preg_replace code but am too noob to findout how to replace the quoted string and introduce escape char which will look like this \"quoted string\". Seriously, I cannot comprehend with the preg_replace with this condition.. where you will find the occurence of double qoute inside the json_encoded string.. Please enlighten me.
I have tried other questions available here but my understanding was not enough.
Also, pls note that I cannot touch the 1 encoding the json object as it is provided by a 3rd party system..
TIA.
EDIT:
Thanks to those who enlighten me...
So this was not possible and I have to drop this one and try to contact the system developer to correct the json encoded string they provided as it was the best option.
Which for a reason I cannot touch
Then you're stuffed. It's broken, and you can't reliably fix it.
I try some preg_replace code
You can't. There's no way for you to know whether a " is actually meant to terminate the string, or meant to be a character in the string.
Stop all attempts to fix this at your end. The end sending you the invalid JSON is the problem. If you "can't touch" it, contact and berate someone who can until they fix it. You might take it as an opportunity to teach them that this is why don't hand-create JSON, or create it with string concatenation, etc. Instead, you build a structure, then use a proper JSON serializer to create the JSON, which will (in this case) put in the necessary escapes (backslashes) so that it looks like this:
[{"item0":"sometext","item1":"sometext too but i have \"quoted string\" inside of me"}]

variable name with 'current' word in php adds special character [duplicate]

I'm using php to look at an XML file that has a URL in it. The URLs look something like this:
https://site.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
When I echo out the URLs, the "&curren" shows up as "¤" (AKA #164, A4 or currency symbol) and the links don't work. This happens even though there isn't a closing semicolon for it. What is the cleanest way to make "&curren" display literally?
Funny enough I ran into the same problem just now and I found this answer. However, I found another solution which might even be better!
Simply put the variable at the beginning of your query string, and you will avoid the &curren completely.
Do:
https://site.com/bacon_report?currentDimension=2&Id=1&report=1&param=1
instead of:
https://site.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
Use the php function urlencode:
urlencode("https://site.com/bacon_report?Id=1&report=1&currentDimension=2&param=1"
will output
https%3A%2F%2Fsite.com%2Fbacon_report%3FId%3D1%26report%3D1%26currentDimension%3D2%26param%3D1
The problem here is escaping - you need to escape the "&" characters. In XML all special characters like <, >, ', " and & should be escaped.
Escape it properly as
https://example.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
..just like in HTML:
WRONG - no escaping
CORRECT - correct escape sequence
So - the cleanest way to show "&curren" in HTML/XML is to properly escape the ampersand, and render it as "&curren".
I think that in this case it is best to use htmlentities because with urlencode you get
https%3A%2F%2Fexample.com%2Fbacon_report%3FId%3D1%26report%3D1%26currentDimension%3D2%26param%3D1
and when applying urldecode, you will still have the &curren symbol
where as with htmlentities the url comes out clean.
https://example.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
I came across this issue while working on technical documentation (in Markdown which gets converted to HTML).
To solve the issue I used a zero-width space character which I copied and pasted from between these brackets (​). That way it appears that there is no space and can include the below without any issues:
/search?query=1&currentLonLat=-74.600291,40.360869

How to get &curren to display literally, not as an HTML entity

I'm using php to look at an XML file that has a URL in it. The URLs look something like this:
https://site.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
When I echo out the URLs, the "&curren" shows up as "¤" (AKA #164, A4 or currency symbol) and the links don't work. This happens even though there isn't a closing semicolon for it. What is the cleanest way to make "&curren" display literally?
Funny enough I ran into the same problem just now and I found this answer. However, I found another solution which might even be better!
Simply put the variable at the beginning of your query string, and you will avoid the &curren completely.
Do:
https://site.com/bacon_report?currentDimension=2&Id=1&report=1&param=1
instead of:
https://site.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
Use the php function urlencode:
urlencode("https://site.com/bacon_report?Id=1&report=1&currentDimension=2&param=1"
will output
https%3A%2F%2Fsite.com%2Fbacon_report%3FId%3D1%26report%3D1%26currentDimension%3D2%26param%3D1
The problem here is escaping - you need to escape the "&" characters. In XML all special characters like <, >, ', " and & should be escaped.
Escape it properly as
https://example.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
..just like in HTML:
WRONG - no escaping
CORRECT - correct escape sequence
So - the cleanest way to show "&curren" in HTML/XML is to properly escape the ampersand, and render it as "&curren".
I think that in this case it is best to use htmlentities because with urlencode you get
https%3A%2F%2Fexample.com%2Fbacon_report%3FId%3D1%26report%3D1%26currentDimension%3D2%26param%3D1
and when applying urldecode, you will still have the &curren symbol
where as with htmlentities the url comes out clean.
https://example.com/bacon_report?Id=1&report=1&currentDimension=2&param=1
I came across this issue while working on technical documentation (in Markdown which gets converted to HTML).
To solve the issue I used a zero-width space character which I copied and pasted from between these brackets (​). That way it appears that there is no space and can include the below without any issues:
/search?query=1&currentLonLat=-74.600291,40.360869

PHP 'addslashes' not behaving as expected

This has been driving be crazy, but I can't seem to find an answer. We run a technical knowledge base that will sometimes include Windows samba paths for mapping to network drives.
For example: \\servername\sharename
When we include paths that have two backslashes followed by each other, they are not escaped properly when running 'addslashes'. My expected results would be "\\\\servername\\sharename", however it returns "\\servername\\sharename". Obviously, when running 'stripslashes' later on, the double backslash prefix is only a single slash. I've also tried using a str_replace("\\", "\", $variable); however it returns "\servername\sharename" when I would expect "\\servername\sharename".
So with addslashes, it ignores the first set of double-backslashes and with str_replace it changes the double-backslashes into a single, encoded backslash.
We need to run addslashes and stripslashes for database insertion; using pg_escape_string won't work in our specific case.
This is running on PHP 5.3.1 on Apache.
EDIT: Example Code
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo addslashes($variable);
This returns: In the box labeled Folder type: \\servername\\sharename
EDIT: Example Code #2
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo str_replace('\\', '\', $variable);
This returns: In the box labeled Folder type: \servername\sharename
I'd also like to state that using a single quotes or double-quotes does not give me different results (as you would expect). Using either or both give me the same exact results.
Does anyone have any suggestions on what I can possibly do?
I think I know where is a problem. Just try to run this one:
echo addslashes('\\servername\sharename');
And this one
echo addslashes('\\\\servername\sharename');
PHP escapes double slashes even with single quotes, because it is used to escape single quote.
Ran a test on the problem you described, and the only way I could get the behavior you desired was to couple a conditional with a regex and anticipate the double slashes at the start.
$str = '\\servername\sharename';
if(substr($str,0,1) == '\\'){
//String starts with double backslashes, let's append an escape one.
//Exclaimation used for demonstration purposes.
$str = '\\'.$str;
echo addslashes(preg_replace('#\\\\\\\\#', '!',$str ));
}
This outputs:
!servername\\sharename
While this may not be an outright answer, it does work and illustrates a difference in how the escape character is treated by these two constructs. If used, the ! could easily be replaced with the desired characters using another regex.
This is not a problem with addslashes, it is a problem with the way you are assigning the string to your variable.
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo $variable;
This returns: In the box labeled Folder type: \servername\sharename
This is because the double backslash is interpreted as an escaped backslash. Use this assignment instead.
$variable = 'In the box labeled Folder type: \\\\servername\\sharename';
I've determined, with more testing, that it indeed is with how PHP is handling hard-coded strings. Since hard-coded strings are not what I'm interested in (I was just using them for testing/this example), I created a form with a single text box and a submit button. addslashes would correctly escape the POST'ed data this way.
Doing even more research, I determined that the issue I was experiencing was with how PostgreSQL accepts escaped data. Upon inserting data into a PostgreSQL database, it will remove any escape characters it is given when it actually places the data in the table. Therefore, stripslashes is not required to remove escape characters when pulling the data back out.
This problem stemmed from code migration from PHP 4.1 (with Magic Quotes on) to PHP 5.3 (with Magic Quotes deprecated). In the existing system (PHP4), I don't think we were aware that Magic Quotes were on. Therefore, all POST data was being escaped already and then we were escaping that data again with addslashes before inserting. When it got inserted into PostgreSQL, it would strip one set of slashes and leave the other, therefore requiring us to stripslashes on the way out. Now, with Magic Quotes off, we escape with addslashes but are not required to use stripslashes on the way out.
It was very hard to organize and determine exactly where the problem lay, so I know this answer is a little off to my original question. I do, however, thank everyone who contributed. Having other people sound off on their ideas always helps to make you think on avenues you may not have on your own.

Categories