在 php 中处理用户输入数据。什么更好?
我试图找出管理用户输入的有关他可能插入的不需要的标签的数据的最佳方法是什么:
- strip_tags() - 标签被删除,并且不会插入数据库
- 中标签被插入到数据库中,但是当读取该字段并将其显示给用户时,我们将使用 htmlspecialchars()
有什么更好的方法,这些方法有什么缺点吗?
问候
I am trying to figure out what is the best way to manage the data a user inputs concerning non desirable tags he might insert:
- strip_tags() - the tags are removed and they are not inserted in the database
- the tags are inserted in the database, but when reading that field and displaying it to the user we would use htmlspecialchars()
What's the better, and is there any disadvantage in any of these?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于您的优先级:
htmlspecialchars()
来显示输出(如果不是更复杂的东西),strip_tags()
它在数据库中 - 这样您将减少需要存储的数据量,并减少在屏幕上显示数据时的处理时间This depends on what your priority is:
htmlspecialchars()
to display the output (if not something more sophisticated)strip_tags()
before you stick it in the database - this way you'll reduce the amount of data that you need to store, and reduce processing time when displaying the data on the screen这个。您通常希望人们能够输入小于号和与号并将它们显示在页面上。在每个文本到 HTML 输出步骤(无论该文本直接来自用户输入,还是来自数据库,或者完全来自其他地方)上的
htmlspecialchars
是实现此目的的正确方法。对于处理输出编码问题来说,弄乱输入是一种完全不合适的策略。当然,您需要不同的转义(或参数化)来将文本放入 SQL 字符串中。
This. You usually want people to be able to type less-than signs and ampersands and have them displayed as such on the page.
htmlspecialchars
on every text-to-HTML output step (whether that text came directly from user input, or from the database, or from somewhere else entirely) is the right way to achieve this. Messing about with the input is a not-at-all-appropriate tactic for dealing with an output-encoding issue.Of course, you will need a different escape — or parameterisation — for putting text in an SQL string.
为保护用户输入而采取的措施完全取决于数据的使用环境。例如:
mysql_real_escape_string()
也能正常工作。上面的最后一点延续到下一点:许多人认为应该始终保留原始输入。当您稍后决定以不同的方式使用数据时,这很有意义,例如,HTML 标记在新上下文中并不是什么大问题。此外,如果您的网站以某种方式受到损害,您还会记录所给的确切输入。
特别与用于在 HTML 页面上显示的用户输入中的 HTML 标记相关:如果用户输入 HTML 标记有任何可能的原因,则只需转义它们即可。如果没有,请在显示前将其剥离。
The measures taken to secure user input depends entirely on in what context the data is being used. For instance:
mysql_real_escape_string()
works decently, as well.The last point above segues into the next point: Many feel that the original input should always be maintained. This makes a lot of sense when, later, you decide to use the data in a different way and, for instance, HTML tags aren't a big deal in the new context. Also, if your site is in some way compromised, you have a record of the exact input given.
Specifically related to HTML tags in user input intended for display on an HTML page: If there is any conceivable reason for a user to input HTML tags, then simply escape them. If not, strip them before display.