何时过滤/清理数据:在数据库插入之前还是在显示之前? [英] When to filter/sanitize data: before database insertion or before display?

查看:125
本文介绍了何时过滤/清理数据:在数据库插入之前还是在显示之前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我准备解决输入数据过滤和消毒问题时,我很好奇是否有最好的(或最常用的)做法?在将数据插入数据库之前过滤/清理数据(HTML,JavaScript等)是更好的方法,还是应该在数据准备好以HTML格式显示时完成?



一些注释:


  • 我在PHP中这样做,但我怀疑这个答案是语言不可知。但是,如果您有任何特定于PHP的建议,请分享!

  • 这不是转义数据库插入数据的问题。



谢谢!

解决方案



我会推荐给用户提交的数据显示用户提交的数据,普遍接受的口头禅是过滤输入,转义输出。在进入数据库之前,不要转义诸如html实体之类的东西,因为您永远不知道HTML何时不会成为您的显示媒介。另外,不同类型的情况需要不同类型的输出转义。例如,在Javascript中嵌入一个字符串需要不同于HTML的转义。这样做可能会让你陷入一种错误的安全感。

因此,基本的经验法则是,在使用之前进行消毒,特别是为了使用。 (请注意,我不是在谈论转义的输出为SQL,只是为了显示,请仍然做转义数据绑定到一个SQL字符串)。

As I prepare to tackle the issue of input data filtering and sanitization, I'm curious whether there's a best (or most used) practice? Is it better to filter/sanitize the data (of HTML, JavaScript, etc.) before inserting the data into the database, or should it be done when the data is being prepared for display in HTML?

A few notes:

  • I'm doing this in PHP, but I suspect the answer to this is language agnostic. But if you have any recommendations specific to PHP, please share!
  • This is not an issue of escaping the data for database insertion. I already have PDO handling that quite well.

Thanks!

解决方案

When it comes to displaying user submitted data, the generally accepted mantra is to "Filter input, escape output."

I would recommend against escaping things like html entities, etc, before going into the database, because you never know when HTML will not be your display medium. Also, different types of situations require different types of output escaping. For example, embedding a string in Javascript requires different escaping than in HTML. Doing this before may lull yourself into a false sense of security.

So, the basic rule of thumb is, sanitize before use and specifically for that use; not pre-emptively.

(Please note, I am not talking about escaping output for SQL, just for display. Please still do escape data bound for an SQL string).

这篇关于何时过滤/清理数据:在数据库插入之前还是在显示之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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