Pass a PHP variable to a JavaScript variable
Asked Answered
F

14

403

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.

Frisian answered 3/10, 2008 at 18:27 Comment(2)
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));Stilla
This is not a duplicate of #23741048. 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)Oxyhydrogen
B
560

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.

Barbwire answered 3/10, 2008 at 21:49 Comment(15)
If you use UTF-8 that's the best solution by far.Oblivion
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.Gynous
If you're not 5.2, try jsonwrapper from boutell.com boutell.com/scripts/jsonwrapper.htmlSyllogize
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.Caril
Be aware that PHP 5.3 now has options for escaping various characters. See example #2 for various outputs: php.net/manual/en/function.json-encode.phpDunnite
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.Aerification
Worked great thanks! Also so others don't run into the same thing I did when using this: Make sure to remove the quotes around your json_encoded php variables you are inserting into javascript because json_encode already includes them.Pauperize
If the string contains new line, then I think it will throw an errorIveson
A plain json_encode() call for escaping output is insecure. Adding JSON_HEX_QUOT | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_TAG as the second parameter helps in some cases, but it still allows you to inject some JS code like "1; alert(10)" or something more harmful in an example like this. Other than proper input validation, I'm not sure what can help that case. Without the second param, injecting any code is trivial.Diplocardiac
I think the best way on PHP 5.4+ to use two good special flags. And of course, the short syntax. Here is it: var myvar = <?=json_encode($myVarValue, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)?>; . The first one tells not to encode forward slash /, the second one prints any utf8 symbols not like xNNNN but just as is.Strake
@FlameStorm: Encode forward slashes, that is useful to prevent </script> injections (!!) as they become <\/script>. Otherwise the script tag is closed prematurely which can be used as part of an attack. - see as well the earlier comment #168714Ranaerancagua
@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.Strake
For those using Laravel, you can use the ultra-simple @json($myVarValue). See "Rendering JSON" under laravel.com/docs/5.6/blade#displaying-dataGaribull
There are edge cases where json_encode() is not enough: docs.zendframework.com/zend-escaper/escaping-javascriptNerva
hello, please does anyone know why I'm getting SyntaxError: expected expression, got '<' when using var a = <?php echo json_encode($_REQUEST["errors"]); ?>;, thank youBifacial
I
27

encode it with JSON

Interpose answered 3/10, 2008 at 18:33 Comment(6)
Probably the easiest way to get this to work 100% of the time. There are too many cases to cover otherwise.Ariadne
Json only works with UTF-8 Charset. So it is not a solution if your website is working in a non UTF-8 EncodingCute
@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 conversionInterpose
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.Arundel
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.Borges
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.Ingles
L
24
function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
Larina answered 3/10, 2008 at 18:38 Comment(2)
I needed this one because I was using the contents of the variable as part of a concatenated javascript expression.Freewheeling
This really helped me.Goodtempered
U
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().

Unsex answered 14/1, 2009 at 13:33 Comment(3)
decodeURIComponent complies with RFC 3986, I believe.Disharoon
This is the correct solution when you parse large strings (ex: html content as string)Kaftan
@RaduGheorghies Why?Headstream
J
12

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(???)" />
Jurkoic answered 23/4, 2011 at 9:32 Comment(4)
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.Valediction
@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) ...Jurkoic
For an HTML attribute, you could do <div onclick="alert(<?php echo htmlspecialchars(json_encode($var));?>" />Arundel
This is not unicode save, check this out: docs.laminas.dev/laminas-escaper/escaping-javascriptLovett
G
6
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>

or

<script>
var myVar = <?= json_encode($myVarValue) ?>;
</script>
Gravelly answered 29/11, 2012 at 14:16 Comment(3)
You must not enclose the encoded value in quotes.Tangle
Note that json_encode escapes forward slashes, meaning that this will never print </script> by accident.Arundel
How it's different from the accepted answer written 4 years prior?Swirsky
C
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'\\"))); 
} 
Comb answered 11/3, 2010 at 16:50 Comment(1)
Me too! These two lines of code is the best thing that happened to php (at least IMHO). Thanks a lot!!Retinite
O
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.

Oogenesis answered 3/10, 2008 at 18:39 Comment(2)
"not to put broken HTML in there", that means escaping 'HTML entities' (at the very least '<' and '&')Interpose
No, just don't close your container DIV prematurely.Oogenesis
S
3

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>
Sagerman answered 19/10, 2012 at 9:50 Comment(2)
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?Rabah
@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.Sagerman
D
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));
    }
    
Disharoon answered 8/1, 2014 at 18:19 Comment(3)
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.Arundel
@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.Disharoon
@Flimm: How this works: <!--<script> causes the legitimate </script> to be treated as code rather than as an ending tag.Disharoon
C
2

You could try

<script type="text/javascript">
    myvar = unescape('<?=rawurlencode($myvar)?>');
</script>
Clepsydra answered 3/10, 2008 at 18:50 Comment(2)
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 transliterationSyllogize
unescape is now deprecated. Use decodeURIComponent instead.Learnt
F
0

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

Filament answered 3/10, 2008 at 18:37 Comment(1)
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.Richelle
D
-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.

Discourage answered 27/8, 2010 at 0:28 Comment(3)
I have been doing this in my previous projects. Next time, I will try to use jQuery data.Restharrow
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.Sagerman
To be safe, you should really do value="<?php echo htmlspecialchars(json_encode($someString));?>".Arundel
P
-3

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>
Promenade answered 3/10, 2008 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.