在将用户输入存储到数据库之前对其进行转义/编码,还是将其按原样存储在数据库中并在检索时进行转义,这样更好? [英] is it better to escape/encode the user input before storing it to database or to store it as it is in database and escape it while retrieving?

查看:210
本文介绍了在将用户输入存储到数据库之前对其进行转义/编码,还是将其按原样存储在数据库中并在检索时进行转义,这样更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用htmlspecialchars()功能来防止XSS攻击.我不知道从下面开始有什么更好的方法将数据存储到数据库中.

I am using htmlspecialchars() function to prevent XSS attacks. I have doubt regarding what is the better method to store the data in database from following.

方法1::应用htmlspecialchars()功能后,存储用户输入的值.使用它,用户输入"<script>"将变为& ltscript& gt;"

Method 1 : Store the user input values after applying htmlspecialchars() function. Using this it user input "<script>" will become "&lt;script&gt;" .

方法2::按原样存储用户输入,并在检索数据并将其显示在页面上时应用htmlspecialchars()方法.

Method 2 : Store the user input as it is and apply htmlspecialchars() method while retrieving the data and displaying it on the page.

我怀疑的原因是,我相信使用方法1会导致数据库开销,而使用方法2时,需要通过php请求一次又一次地转换数据.所以我不确定哪个更好.

The reason for my doubt is that I believe using method 1 there will be overhead on database, while using method 2 data need to be converted again and again when requested through php. So I am not sure which one is better.

有关更多信息,我正在使用htmlspecialchars($val, ENT_QUOTES, "UTF-8"),以便也可以转换'和'.

For more information, I am using htmlspecialchars($val, ENT_QUOTES, "UTF-8") so that will convert ' and " as well.

请帮助我清除我的疑问.如果可能,还提供解释.

Please help me clear my doubt. Also provide explanation if possible.

谢谢.

推荐答案

一个更好的 原因是,在将其截断以适合某个空间时,您会被诸如"&quo..."的可憎之物卡住.抵制尝试摆弄数据的诱惑超过最低要求.如果您担心要重新处理数据,请对其进行缓存.

An even better reason is that on truncating to fit a certain space you'll get stuck with abominations such as "&quo...". Resist the temptation to fiddle with your data more than the minimum required. If you're worried about reprocessing the data, cache it.

这篇关于在将用户输入存储到数据库之前对其进行转义/编码,还是将其按原样存储在数据库中并在检索时进行转义,这样更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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