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>';
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.