I am passing a string variable from php to javascript.
The string contains "
But javascript doesn't get it.
How can I escape this character?
UPD:
To be more clear, first I don't want to make many changes in the code (not written by me)...
The string is passed this way:
var string = '<? echo $string;?>' ;
Single quotes are used. Maybe there is a way to change smth. in the string itself?
You could use the json_encode method:
<script type="text/javascript">
var value = <?php echo json_encode($someValue); ?>;
alert(value);
</script>
Assuming a string delimited using double quotes, add_slashes will do the job in the particular case.
Wrapping the data in an associative array, running it through json_encode and altering the JS to expect the changed data structure is a safer approach though (since that will take care of other characters which are significant, such as literal new lines).
(Technically speaking, with the current implementation of json_encode you could skip wrapping it in an associative array … but a plain string isn't valid JSON and I'm inclined to avoid depending on a function that is supposed to generate JSON not throwing an exception when given a data structure that can't be turned into JSON).
If you are embedding the script in an HTML document you will also have to take steps to ensure that the resulting JS doesn't contain any HTML that could cause issues (such as " in an script included as an attribute value).
Use urlencode() function in php code to pass the string to javascript code and decodeuri() in javascript to decode that string.
Related
I have a php associative array containing strings as values and I encode it to JSON and store it in an html-data attribute. That is read by some JS.
So far so good.
Now, I need to use single quotes for the data attribute, otherwise the context switches.
<section id="settings" data-settings='{"some":"val"}'>
</section>
The question is, can I rely on the json_encode() function of php to encode strings always with double quotes? Surprisingly, I can't seem to find information on this. I only find articles from people having issues with quotes in the array values.
Thanks in advance.
Yes, as defined in the JSON spec, the delimiter will always be ". However, values may contain ' characters, which would break your HTML. To keep it simple and not worry about what might or mightn't pose an issue, HTML-escape your values!
<section data-settings="<?= htmlspecialchars(json_encode($foo)); ?>"></section>
This is guaranteed to work, always, no matter what values you pipe in or how you encode them.
NOTE that htmlspecialchars will by default only encode ", not '; so you must use " as the delimiter in HTML (or change the default escaping behavior).
Double-quotes is just convention - standard in JSON in many languagues. So if you want to store JSON in HTML attribute with double-quotes. You can encode that
In PHP
$encoded_json = base64_encode(json_encode($var));
In HTML
<section id="settings" data-settings='<?=$encoded_json?>'>
In JS
var variable = JSON.parse(atob(encoded_json));
I have this URL parameter:
KKe%7bZoE_%24g)tjm%40
When I put it into a variable and echo it, the result is:
KKe{ZoE_$g)tjm#
How to avoid that?
Data in $_GET is already URL-decoded. If you require the original string, get it from $_SERVER['QUERY_STRING']. Note that you will have to process the query string yourself though, including breaking down the individual components.
Alternatively, use rawurlencode($_GET[..]) to re-encode the value; which may or may not produce slightly differently encoded values than you originally got.
Test it with html_entity_decode - it helpt me a lot with my inputs.
If the string is not shown as it is, you have urlencode() or htmlentities() somewhere in your code. Check that, you shouldn't encode html entities before echoing if you want the string to be intact.
I would like to call a function onclick, but with a json_encode parameter like this:
<a href="#" onclick="javascript:table1Modif(<?php echo substr(json_encode($res['base']),1,-1); ?>);return false;">
And the Jquery function just alert the parameter:
<script>
function table1Modif(key){
$('#table1').html(function() {
alert(key);
});
}
</script>
But I have an "undefined" error!
I am sure that it's due to json_encode, but I don't know how to solve it.
Thank you!
It looks like you are passing a string to json_encode in order to generate a JavaScript string literal (which is not valid JSON).
You are using substr to remove the quotes from this string.
JavaScript will therefore see an identifier (which in that context will be treated as a variable).
You need a string literal, so the first thing to do is remove the substr call.
This will create a new problem. You are inserting the string into an HTML document, but not expressing it as HTML. The " character at the start of the string literal will therefore be treated as end of attribute value, which you don't want.
When inserting non-HTML content into an HTML document you need to express it as HTML. Run the code through the htmlspecialchars function to do this.
onclick="table1Modif(<?php
echo htmlspecialchars(
json_encode($res['base'])
);
?>);return false;"
Incidently, I've removed the entirely useless javascript: label. You don't have a loop to break or continue from so it isn't doing anything. While you're at it, you should replace href="#" with something more sensible. Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
I am using json_encode in PHP to encode an URL
$json_string = array ('myUrl'=> 'http://example.com');
echo json_encode ($json_string);
The above code generates the following JSON string:
{"myUrl":"http:\/\/example.com"}
Rather than
{"myUrl":"http://example.com"}
I am just newbie, which output is correct? Is JSON parser able to evaluate the second output correctly?
According to https://www.json.org/, one should escape that character, although it is not strictly necessary in JavaScript:
Also read this related bug report on php.net for a brief discussion.
See 2.5 of the RFC:
All Unicode characters may be placed
within the quotation marks except for
the characters that must be escaped:
quotation mark, reverse solidus, and
the control characters (U+0000 through
U+001F).
Any character may be escaped.
So it doesn't sound like it needs to be escaped, but it can be, and the website (and a text diagram in the RFC) illustrates it as being escaped.
My guess is that the writers of that function added that unnecessary encoding through nothing more than plain ignorance. Escaping forward slashes is not required.
A surprisingly large number of programmers I've known are just as bad with keeping their slashes straight as the rest of the world. And an even greater number are really poor with doing encoding and decoding properly.
Update:
After doing some searches, I came across this discussion. It brings up a good point that escaping a / is sometimes necessary for bad HTML parsers. I've come across a problem once where when IE 6 incorrectly handles content like this:
<script>
var json = { scriptString: "<script> /* JavaScript here */ </script>" };
</script>
IE 6 would see the </script> inside of the string and close out the script tag too early. Thus, this is more IE 6 safe (though the opening script tag in string might also break things... I can't remember):
<script>
var json = { scriptString: "<script> \/* JavaScript here *\/ <\/script>" };
</script>
And they also say that some bad parsers would see the // in http:// and treat the rest of the line like a JavaScript comment.
So it looks like this is yet another case of Internet technologies being hijacked by Browser Fail.
If you are using php 5.4 you can use json_encode options. see the manual.
Several options added in php 5.3 but JSON_UNESCAPED_SLASHES in 5.4.
I think this solves your problem
json_encode ($json_string, JSON_UNESCAPED_SLASHES );
You can see the documentation:
https://www.php.net/manual/en/function.json-encode.php https://www.php.net/manual/en/json.constants.php
I see another problem here. The string result {"myUrl":"http://example.com"} should not have the member name myUrl quoted. In JavaScript and JSON, I think all object literal member ids are unquoted strings. So, I would expect the result to be {myUrl:"http://example.com"}.
This seems too big a bug in PHP, so I must be wrong.
Edit, 2/11/11: Yes, I'm wrong. JSON syntax requires even the field names to be in double quotation marks.
For example i've a php script with this content:
<?php
$msg = addslashes("I'm a message. The what happened >:(");
echo "<script>alert($msg); return false;</script>";
?>
But the alert get broken by the last "(". How can i solve this?
You should enclose alert parameter with quotes:
echo "<script>alert('$msg'); return false;</script>";
What your code outputs to the browser was:
<script>alert(The what happened >:(); return false;</script>
which is not a valid javascript, after putting the quotes, it becomes:
<script>alert('The what happened >:('); return false;</script>
which is valid javascript.
You need to put it in a JavaScript string, otherwise it gets interpreted like this, which is meaningless and causes an error:
<script>alert(The what happened >:(); return false;</script>
Notice the single quotes in the alert() call which denote a JavaScript string (double quotes work too):
<?php
$msg = "The what happened >:(";
echo "<script>alert('$msg'); return false;</script>";
?>
It is also a good idea to escape the content inside to mitigate XSS, using htmlspecialchars().
The other answers are along the right lines, but it is not sufficient to just put quotes around the string, if it can be any arbitrary string. If the string itself contains a quote, backslash, or newline, that will break the JavaScript string literal. If the string contains </script (or just </ in some cases) that will break the <script> block. In either case, if user-supplied input is involved, that gives you a big old cross-site-scripting security hole.
Whilst you may not need it for this specific value of $msg, it's a good idea to get used to JS-string-literal-escaping any text you output into a JS string. Whilst you can do this manually by adding backslashes, it's generally much easier to just use the built-in JSON encoder, which will work for other types like arrays and objects as well as strings.
<script type="text/javascript">
alert(<?php echo json_encode($msg); ?>);
return false; // huh? return, in a <script> block??
</script>
alert() accepts a string argument; you must enclose the text you're passing to it in quotes (either single or double) and insure that any matching quotes within the string are escaped by backslashes.
In your case single quotes would suffice:
echo "<script>alert('$msg'); return false;</script>";
Depending on the context, you might also just do:
<?php
$msg = "The what happened >:(";
?>
<script>alert("<?php echo $msg ?>"); return false;</script>
If there is no need to echo HTML or JavaScript code, then don't do it. It is easier to maintain .