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

PhpJavascriptEscapingNewline

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

encode it with JSON

Solution 3 - Php

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

Solution 4 - Php

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

Solution 5 - Php

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

Solution 6 - Php

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

or

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

Solution 7 - Php

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

Solution 8 - Php

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>

Solution 9 - Php

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.

Solution 10 - Php

You could try

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

Solution 11 - Php

  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));
     }
    

Solution 12 - Php

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

Solution 13 - Php

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.

Solution 14 - Php

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

Check out [XTemplates][1]. [1]: http://www.phpxtemplate.org It's a nice, open source, lightweight, template engine.

Your HTML/JS there would look like this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid LaingView Question on Stackoverflow
Solution 1 - PhpbobwienholtView Answer on Stackoverflow
Solution 2 - PhpJavierView Answer on Stackoverflow
Solution 3 - PhpmicahwittmanView Answer on Stackoverflow
Solution 4 - Phppr1001View Answer on Stackoverflow
Solution 5 - PhpgiraffView Answer on Stackoverflow
Solution 6 - PhpKldView Answer on Stackoverflow
Solution 7 - Phpuser291681View Answer on Stackoverflow
Solution 8 - PhpCraig FrancisView Answer on Stackoverflow
Solution 9 - PhpDiodeus - James MacFarlaneView Answer on Stackoverflow
Solution 10 - PhpJacobView Answer on Stackoverflow
Solution 11 - PhpRy-View Answer on Stackoverflow
Solution 12 - PhpChris MacDonaldView Answer on Stackoverflow
Solution 13 - PhpioTusView Answer on Stackoverflow
Solution 14 - PhpAdamView Answer on Stackoverflow