ChatGPT解决这个技术问题 Extra ChatGPT

Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]

This question already has answers here: How do I pass variables and data from PHP to JavaScript? (19 answers) Closed 8 years ago. The community reviewed whether to reopen this question 8 months ago and left it closed: Original close reason(s) were not resolved

What is the easiest way to encode a PHP string for output to a JavaScript variable?

I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.

Normally, I would just construct my JavaScript in a PHP file, à la:

<script>
  var myvar = "<?php echo $myVarValue;?>";
</script>

However, this doesn't work when $myVarValue contains quotes or newlines.

Just wanted to point out you can use utf8_encode() before passing the string to json_encode. That's what I'm doing: echo json_encode(utf8_encode($msg));
This is not a duplicate of stackoverflow.com/questions/23740548/…. The latter speaks about AJAX etc. and networking questions, whereas here it's about encoding/escaping/quotes and newlines. Let's reopen? (Btw, here the accepted is short, works good and has many hundreds of votes)

F
Flimm

Expanding on someone else's answer:

<script>
  var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

PHP 5.2.0 or greater

$myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.


If you use UTF-8 that's the best solution by far.
It is important that the implementation of json_encode escapes the forward slash. If it didn't, this wouldn't work if $myVarValue was "". But json_encode does escape forward slashes, so we're good.
If you're not 5.2, try jsonwrapper from boutell.com boutell.com/scripts/jsonwrapper.html
Please note that if you use this in onclick attributes and the like, you need to pass the result of json_encode to htmlspecialchars, like the following: htmlspecialchars(json_encode($string),ENT_QUOTES,'utf-8') or else you could get problems with, for example, &bar; in foo()&&bar; being interpreted as an HTML entity.
@hakre: But how PHP string contains "...</script>..." can become JS non-string </script> instead of just JS string "...</script>..." after PHP's json_encode? It always add quotes for string. So, var x = "...</script>..."; is just an JS string. No break.
J
Javier

encode it with JSON


Probably the easiest way to get this to work 100% of the time. There are too many cases to cover otherwise.
Json only works with UTF-8 Charset. So it is not a solution if your website is working in a non UTF-8 Encoding
@nir: on one hand, i don't know any reason to use any other encoding, on the other hand, a full JSON encoder also manages any needed charset conversion
Encoding it with JSON is not enough, you also have to make sure that any Javascript string which contains </script> (case insensitive) is dealt with properly.
Encoding a single scalar value with JSON won't force it to an object - you just get a utf-8 string. For example let's say your php code looks like this: $x=""; and your HTML looks like this: the result in the browse will be: Note the double quotes ahd the escaped slash.
m
micahwittman
function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}

I needed this one because I was using the contents of the variable as part of a concatenated javascript expression.
This really helped me.
p
pr1001

I have had a similar issue and understand that the following is the best solution:

<script>
    var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>");
</script>

However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP's rawurlencode() function is supposed to comply with RFC 1738, while there appear to have been no such effort with Javascript's decodeURIComponent().


decodeURIComponent complies with RFC 3986, I believe.
This is the correct solution when you parse large strings (ex: html content as string)
@RaduGheorghies Why?
g
giraff

The paranoid version: Escaping every single character.

function javascript_escape($str) {
  $new_str = '';

  $str_len = strlen($str);
  for($i = 0; $i < $str_len; $i++) {
    $new_str .= '\\x' . sprintf('%02x', ord(substr($str, $i, 1)));
  }

  return $new_str;
}

EDIT: The reason why json_encode() may not be appropriate is that sometimes, you need to prevent " to be generated, e.g.

<div onclick="alert(???)" />

Escaping every single character worked for me. json_encode doesn't handle backslashes very well. If you need to pass something like a regular expression from mysql to javascript as a parameter then this seems the best way.
@kristoffer-ryhl correctly remarks that dechex doesn't work for '\t' (= '\x08'), so I edited it to use sprintf. However, this still doesn't seem to work for UTF-8 characters (this would require using '\u' instead) ...
For an HTML attribute, you could do <div onclick="alert(<?php echo htmlspecialchars(json_encode($var));?>" />
This is not unicode save, check this out: docs.laminas.dev/laminas-escaper/escaping-javascript
S
Salman A
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>

or

<script>
var myVar = <?= json_encode($myVarValue) ?>;
</script>

You must not enclose the encoded value in quotes.
Note that json_encode escapes forward slashes, meaning that this will never print </script> by accident.
S
SLaks

Micah's solution below worked for me as the site I had to customise was not in UTF-8, so I could not use json; I'd vote it up but my rep isn't high enough.

function escapeJavaScriptText($string) 
{ 
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\"))); 
} 

Me too! These two lines of code is the best thing that happened to php (at least IMHO). Thanks a lot!!
R
Ry-

Don't run it though addslashes(); if you're in the context of the HTML page, the HTML parser can still see the </script> tag, even mid-string, and assume it's the end of the JavaScript:

<?php
    $value = 'XXX</script><script>alert(document.cookie);</script>';
?>

<script type="text/javascript">
    var foo = <?= json_encode($value) ?>; // Use this
    var foo = '<?= addslashes($value) ?>'; // Avoid, allows XSS!
</script>

Maybe I'm making a dumb mistake, but when I try to execute this code, I get the following console error SyntaxError: expected expression, got '<' ONLY when I'm referencing an external .js file, when it's inilne, it works fine. Thoughts?
@RADMKT Just a guess, but if it's a .js file it probably isn't using PHP. Might be worth loading the external JS file in the web browser to see the code output.
D
Diodeus - James MacFarlane

You can insert it into a hidden DIV, then assign the innerHTML of the DIV to your JavaScript variable. You don't have to worry about escaping anything. Just be sure not to put broken HTML in there.


"not to put broken HTML in there", that means escaping 'HTML entities' (at the very least '<' and '&')
No, just don't close your container DIV prematurely.
J
Jacob

You could try

<script type="text/javascript">
    myvar = unescape('<?=rawurlencode($myvar)?>');
</script>

Doesn't completely work. Try with this string::: I'm wondering "hey jude" 'cause 1 + 1 < 5 ::: we still get < so not a 100% bidirectional transliteration
unescape is now deprecated. Use decodeURIComponent instead.
R
Ry-

Don’t. Use Ajax, put it in data-* attributes in your HTML, or something else meaningful. Using inline scripts makes your pages bigger, and could be insecure or still allow users to ruin layout, unless… … you make a safer function: function inline_json_encode($obj) { return str_replace('

htmlspecialchars

Description

string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.

The translations performed are:

* '&' (ampersand) becomes '&amp;'
* '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
* ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.
* '<' (less than) becomes '&lt;'
* '>' (greater than) becomes '&gt;'

http://ca.php.net/htmlspecialchars


This will only be the right solution if the content of the JS variable is actually supposed to be HTML, where a string token like & has meaning. Otherwise, it might be best to not convert them to entities.
i
ioTus

I'm not sure if this is bad practice or no, but my team and I have been using a mixed html, JS, and php solution. We start with the PHP string we want to pull into a JS variable, lets call it:

$someString

Next we use in-page hidden form elements, and have their value set as the string:

<form id="pagePhpVars" method="post">
<input type="hidden" name="phpString1" id="phpString1" value="'.$someString.'" />
</form>

Then its a simple matter of defining a JS var through document.getElementById:

<script type="text/javascript" charset="UTF-8">
    var moonUnitAlpha = document.getElementById('phpString1').value;
</script>

Now you can use the JS variable "moonUnitAlpha" anywhere you want to grab that PHP string value. This seems to work really well for us. We'll see if it holds up to heavy use.


I have been doing this in my previous projects. Next time, I will try to use jQuery data.
remember to htmlencode your $someString... and while this is fine for input @value's, you have to be extra careful with href/src/onclick type attributes (try to white-list), as they can go straight into using the javascript: protocol, which is not protected against with html encoded values.
To be safe, you should really do value="<?php echo htmlspecialchars(json_encode($someString));?>".
C
Chandru

If you use a templating engine to construct your HTML then you can fill it with what ever you want!

Check out XTemplates. It's a nice, open source, lightweight, template engine.

Your HTML/JS there would look like this:

<script>
    var myvar = {$MyVarValue};
</script>