使用strip_tags()防止XSS? [英] Prevent XSS with strip_tags()?

查看:102
本文介绍了使用strip_tags()防止XSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP Web应用程序.我不想允许用户将HTML发布到我的网站.

I have a PHP web applications. I do NOT want to allow users to post HTML to my site.

如果仅在保存到数据库之前对所有数据运行strip_tags(),strip_tags()就足以防止XSS吗?

If I simply run strip_tags() on all data prior to saving into my database, will strip_tags() be enough to prevent XSS?

我之所以问,是因为我不清楚是否可以禁止XSS来阅读 strip_tags的文档.浏览器似乎允许将<0/script>(是,零)作为有效HTML的错误.

I ask because it's unclear to me from reading the documentation of strip_tags if XSS is prevented. There seems to be some bug with browser allowing <0/script> (yes, a zero) as valid HTML.

更新

我意识到我可以对所有输出的数据简单地运行htmlspecialchars;但是,我的想法是-既然我不想首先允许HTML,那么一劳永逸地(在学术上更好)清理数据,然后再保存到数据库中,然后每次都要担心无论数据是否安全,我都会输出数据.

I realize that I can simply run htmlspecialchars on all outputted data; however, my thought is that - since I don't want to allow HTML in the first place, it's simply easier (and academically better) to clean my data once and for all, before saving in my database, then have to worry every time I output the data if the data is safe or not.

推荐答案

我强烈不同意它的学术性".

I strongly disagree it's "academically better".

  • 它破坏了用户的输入(想象一下,如果他们清除"了所有标签中的帖子,那么对于本次讨论来说,StackOverflow将会是无用的).

  • It breaks user input (imagine how useless StackOverflow would be for this discussion if they "cleaned" posts from all tags).

在HTML中插入的文本(仅删除了标签)将无效. HTML也需要转义&.

Text inserted in HTML with only tags stripped will be invalid. HTML requires & to be escaped as well.

HTML甚至都不安全! strip_tags()不足以保护属性中的值,例如<input value="$foo">可能会被$foo = " onfocus="evil()所利用(不需要<>!)

It's not even safe in HTML! strip_tags() is not enough to protect values in attributes, e.g., <input value="$foo"> might be exploited with $foo = " onfocus="evil() (no <,> needed!)

因此正确的解决方案是根据所生成语言的要求转义数据.当您具有纯文本并生成HTML时,应使用htmlspecialchars()等将文本转换为HTML.生成电子邮件时,应将文本转换为带引号的可打印格式,依此类推.

So the correct solution is to escape data according to requirements of language you're generating. When you have plain text and you're generating HTML, you should convert text to HTML with htmlspecialchars() or such. When you're generating e-mail, you should convert text to quoted-printable format, and so on.

这篇关于使用strip_tags()防止XSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆