I echo a PHP value into a JavaSript string, like this:
var x = '<?php echo addcslashes($_GET['value'], "'") ?>';
It works just fine, but when I set $_GET['value'] as "><script>alert('hi')</script> for example, I got:
Uncaught SyntaxError: Invalid or unexpected token
In DevTools, the string looks properly escaped, but is not, because it halts the rest of JS code.
var x = '"><script>alert(\'hi\')</script>';
1 Answer 1
The contiguous characters </script> cannot exist in an inline Javascript tag. The HTML markup is parsed before the Javascript, and </script> in the HTML markup after the start of a <script> tag indicates the end of that tag.
You can concatenate instead, so that, for example, your text would result in
var x = '"><script>alert(\'hi\')</scr' + 'ipt>';
by using str_replace:
$withSlashes = addcslashes($_GET['value'], "'");
$xContent = str_replace('</script>', "</scr' + 'ipt>", $withSlashes);
...
var x = '<?php echo $xContent ?>';
But it would be preferable not to dynamically construct Javascript code. Consider using data attributes instead, and to separate the Javascript into its own separate file, eg
<script
src="script.js"
data-x="<?php echo addcslashes($_GET['value'], "'") ?>"
></script>
(if you use this method, remember to properly escape "s if they can exist in the result)
</script>cannot exist in an inline Javascript<script>tag. Consider inserting the data throughdata-attributes, or (worse) ajax, though you could also concatenate the parts on either side of the</script>var x = '</script>'could be something else than a string, from the browser point of view? You should post it as answer<\/script>works, see stackoverflow.com/questions/28259389/…