什么时候适合转义 html 个实体?

When is it appropriate to escape html entities?

在我的服务器端应用程序中,每个输出都通过 htmlentities 函数传递。这样我就可以确保我的应用程序是 xss 安全的。

但是为什么输入不能正确显示htmlentities?例如,这行代码:

  <input class="form-control" placeholder="name"    id="name" />
name.value = '&lt;script&gt;'

注意:&lt;script&gt; = htmlentities("<script>");

此代码在栏内显示单词 &lt;script&gt;。但我希望看到 <script>。对吗?

错了。 htmlentities() 完成将字符转换为 HTML 实体的工作。

看下面的例子,自己看看

<input type="text" value="<?php echo htmlentities("<script>"); ?>" />
<input class="form-control" placeholder="name"    id="name" />
<input class="form-control" placeholder="name"    id="address" />
<script type="text/javascript">
    document.getElementById("name").value = "<?php echo htmlentities("<script>"); ?>".replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
    document.getElementById("address").value = "<?php echo htmlentities("<script>"); ?>";
</script>

不同之处在于您使用 javascript 来更新 html 元素的值,而 javascript 只是将转义值放在框中。关键是你必须对你的案例中的转义实体进行转义。