转义除
之外的所有 HTML
我正在尝试在页面上显示评论,但遇到了一些问题。
我试图处理本质上有两种不同类型的评论:
(1) XSS 类型.. 例如 < /代码>。这可以很容易地处理,方法是在它进入数据库之前对其进行转义,然后在其上运行 stripslashes 和 htmlentities。
(2) 带有
的注释在其中中断。当数据存储到数据库中时,我在其上运行 nl2br,因此数据看起来像 hi
。但是,当我显示此评论时,
hello
etc
并没有像我希望的那样变成分页符。
知道该怎么做吗?我应该注意,关闭 htmlentities 可以修复第二种类型,但第一种类型会作为纯 html 执行并显示警报对话框。
谢谢, 菲尔
I am trying to display comments on a page and am having some trouble.
There are essentially two different types of comments I am trying to handle:
(1) The XSS type.. e.g. <script type="text/javascript">alert('hi')</script>
. This is handled fairly easily by escaping it before it gets into the database and then running stripslashes and htmlentities on it.
(2) The comment with <br>
breaks in it. When the data is stored into the database, I am running nl2br on it so the data looks like hi<br>hello<br><br>etc
. However, when I display this comment, the <br>
s do not turn into page breaks like I want them to.
Any idea what to do? I should note that turning off htmlentities fixes the second type, but the first type then is executed as pure html and displays an alert dialog.
Thanks,
Phil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想删除不需要的标签,可以尝试
strip_tags
。它支持allowable_tags
,因此您可以指定任何不想被删除的标签。 手册中的示例:因此,在转换完所有内容之后
\n
作为换行符,您不必担心它被删除。可能不是你想要的,但希望它能提供一个想法。If you want to remove unwanted tags you can try
strip_tags
. It supportsallowable_tags
so you can specify any tags that you don't want to be stripped. A sample from the manual:So after you've converted all
\n
to be line breaks you dont have to worry about it being stripped. May not be what you want but hope it gives an idea.一种方法:将
替换为占位符,例如\n
。然后做htmlentities来清理html代码。最后,将\n
替换为
以恢复换行符。One method: Replace
<br>
with a placeholder, like\n
. Then do htmlentities to clean up html code. Finally, replace\n
back with<br>
to recover the line breaks.