1

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>';
asked Jan 16, 2019 at 8:30
4
  • 1
    The contiguous characters </script> cannot exist in an inline Javascript <script> tag. Consider inserting the data through data- attributes, or (worse) ajax, though you could also concatenate the parts on either side of the </script> Commented Jan 16, 2019 at 8:32
  • Maybe because you have an extra '>' in front of your <script> tag? Commented Jan 16, 2019 at 8:32
  • @CertainPerformance interresting and understandable behaviour. The browser doesn't know what kind of script language it is, so var x = '</script>' could be something else than a string, from the browser point of view? You should post it as answer Commented Jan 16, 2019 at 8:39
  • FYI: Using <\/script> works, see stackoverflow.com/questions/28259389/… Commented Jan 16, 2019 at 8:50

1 Answer 1

3

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)

answered Jan 16, 2019 at 8:45
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.