405

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.

0

14 Answers 14

561

Expanding on someone else's answer:

<script>
  var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>;
</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.

Please note that if you use this in html attributes like onclick, you need to pass the result of json_encode to htmlspecialchars(), like the following:

htmlspecialchars(json_encode($string), ENT_QUOTES);

or else you could get problems with, for example, &bar; in foo()&&bar; being interpreted as an HTML entity.

Sign up to request clarification or add additional context in comments.

14 Comments

It is important that the implementation of json_encode escapes the forward slash. If it didn't, this wouldn't work if $myVarValue was "</script>". 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
If you're using this in portable (e.g. library) code, there's one caveat. json_encode() has been reported as broken. It's fixed for me (5.4.4-7 on debian), but I don't know about earlier versions.
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.
|
26

encode it with JSON

5 Comments

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.
My only qualm with this is that encoding it with json will force it to an object. In practice, its easier to understand, but when you get to complex arrays of data, specifically that of reading SQL results out from a database, the programmer will need more indepth knowledge of javascript to efficiently handle the data. Essentially what I am saying is that an example of the usage scenario would be great.
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="<script>alert('xss!');</script>"; and your HTML looks like this: <script>var x=<?= json_encode($x);?></script> the result in the browse will be: <script>var x="<script>alert('xss!');<\/script>"</script> Note the double quotes ahd the escaped slash.
24
function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}

Comments

22

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().

1 Comment

decodeURIComponent complies with RFC 3986, I believe.
11

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(???)" />

4 Comments

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
6
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>

or

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

3 Comments

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.
How it's different from the accepted answer written 4 years prior?
4

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'\\"))); 
} 

1 Comment

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

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.

2 Comments

"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.
3
  1. 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…

  2. … you make a safer function:

    function inline_json_encode($obj) {
        return str_replace('<!--', '<\!--', json_encode($obj));
    }
    

3 Comments

I'm pretty sure that <!-- does not need to be escaped within a script block, the only thing that you need to watch out for within a valid Javascript string literal is </script>, and json_encode never outputs that because it escapes forward slashes.
@Flimm: Did you look at the codepad link? Try <script>console.log("<!--<script>")</script><script>console.log(")/;alert('execute arbitrary code here');<!---->")</script>, where the two strings passed to console.log are user-provided (i.e. the template looks like <script>console.log({{ s1 }})</script><script>console.log({{ s2 }})</script>, where $s1 and $s2 come from a bad JSON encoder). Granted, the second string contains an unescaped forward slash and the example is utterly contrived, but a malicious user could still cause a syntax error like this.
@Flimm: How this works: <!--<script> causes the legitimate </script> to be treated as code rather than as an ending tag.
2

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>

2 Comments

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.
1

You could try

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

2 Comments

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

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

1 Comment

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 &amp; has meaning. Otherwise, it might be best to not convert them to entities.
-1

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.

3 Comments

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));?>".
-4

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.