php 中 JavaScript 的转义括号
例如,我有一个包含以下内容的 php 脚本:
<?php
$msg = addslashes("I'm a message. The what happened >:(");
echo "<script>alert($msg); return false;</script>";
?>
但是警报被最后一个“(”破坏了。我该如何解决这个问题?
For example i've a php script with this content:
<?php
$msg = addslashes("I'm a message. The what happened >:(");
echo "<script>alert($msg); return false;</script>";
?>
But the alert get broken by the last "(". How can i solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该用引号将
alert
参数括起来:您的代码输出到浏览器的内容是:
which is not a valid javascript,加上引号后,它会变成:
which is valid javascript。
You should enclose
alert
parameter with quotes:What your code outputs to the browser was:
which is not a valid javascript, after putting the quotes, it becomes:
which is valid javascript.
您需要将其放入 JavaScript 字符串中,否则它会像这样被解释,这是没有意义的并会导致错误:
注意
alert()
调用中的单引号表示 JavaScript 字符串(双引号)工作也):使用
htmlspecialchars()
转义内部内容以减轻 XSS 也是一个好主意。You need to put it in a JavaScript string, otherwise it gets interpreted like this, which is meaningless and causes an error:
Notice the single quotes in the
alert()
call which denote a JavaScript string (double quotes work too):It is also a good idea to escape the content inside to mitigate XSS, using
htmlspecialchars()
.其他答案都是正确的,但是如果字符串可以是任意字符串,则仅在字符串周围加上引号是不够的。如果字符串本身包含引号、反斜杠或换行符,则会破坏 JavaScript 字符串文字。如果字符串包含
(或者在某些情况下仅包含
),则会破坏
块。在任何一种情况下,如果涉及用户提供的输入,都会给您带来一个很大的旧跨站点脚本安全漏洞。
虽然您可能不需要它来获取
$msg
的这个特定值,但习惯将您输出到 JS 字符串中的任何文本进行 JS 字符串转义是一个好主意。虽然您可以通过添加反斜杠来手动执行此操作,但通常使用内置 JSON 编码器要容易得多,该编码器适用于数组、对象以及字符串等其他类型。The other answers are along the right lines, but it is not sufficient to just put quotes around the string, if it can be any arbitrary string. If the string itself contains a quote, backslash, or newline, that will break the JavaScript string literal. If the string contains
</script
(or just</
in some cases) that will break the<script>
block. In either case, if user-supplied input is involved, that gives you a big old cross-site-scripting security hole.Whilst you may not need it for this specific value of
$msg
, it's a good idea to get used to JS-string-literal-escaping any text you output into a JS string. Whilst you can do this manually by adding backslashes, it's generally much easier to just use the built-in JSON encoder, which will work for other types like arrays and objects as well as strings.alert()
接受一个字符串参数;您必须将传递给它的文本括在引号(单引号或双引号)中,并确保字符串中任何匹配的引号都用反斜杠转义。在你的情况下,单引号就足够了:
alert()
accepts a string argument; you must enclose the text you're passing to it in quotes (either single or double) and insure that any matching quotes within the string are escaped by backslashes.In your case single quotes would suffice:
根据上下文,您也可以这样做:
如果不需要回显 HTML 或 JavaScript 代码,则不要这样做。更容易维护。
Depending on the context, you might also just do:
If there is no need to echo HTML or JavaScript code, then don't do it. It is easier to maintain .