在插入MySQL之前使用htmlspecialchars()很好吗? [英] Is it good to use htmlspecialchars() before Inserting into MySQL?

查看:345
本文介绍了在插入MySQL之前使用htmlspecialchars()很好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此我有些困惑.我一直在阅读有关htmlspecialchars()的信息,并计划将其用于textareas POST来防止XSS攻击.我知道通常htmlspecialchars()用于生成发送到浏览器的HTML输出.但是我不确定的是:

I am a little confused on this. I have been reading about htmlspecialchars() and I am planning to use this for the textareas POST to prevent XSS attack. I understand that usually htmlspecialchars() are used to generate the HTML output that is sent to the browser. But what I am not sure is:

1)在将数据插入MySQL之前,对用户输入的数据使用htmlspecialchars()是安全的做法吗?我已经在使用带有参数化值的PDO准备好的语句来防止SQL注入.

1) Is it a safe practice to use htmlspecialchars() to the user input data before I insert it into MySQL? I am already using PDO prepared statement with parameterized values to prevent SQL Injection.

2)或者,我真的不需要担心使用htmlspecialchars()插入值(只要已对它们进行了参数化),而仅当我从MySQL获取结果并将其显示给用户时才使用htmlspecialchars()吗?

2) Or, I really dont need to worry about using htmlspecialchars() to inserted values (provided they are parameterized) and only use htmlspecialchars() when I fetch results from MySQL and display it to users?

推荐答案

正如其他人指出的那样,#2是正确的答案.保持它为原始"状态直到需要时,然后适当地逃脱.

As others have pointed out, #2 is the correct answer. Leave it "raw" until you need it, then escape appropriately.

要详细说明原因(我将重复/总结其他文章),让我们将场景1推至逻辑上的极限.

To elaborate on why (and I will repeat/summarise the other posts), let's take scenario 1 to its logical extreme.

当有人输入"' OR 1=1 <other SQL injection> --"时会发生什么.现在也许您决定因为使用SQL而应该为SQL编码(也许因为没有使用参数化语句).因此,现在您必须混合使用(或决定使用)SQL& HTML编码.

What happens when someone enters " ' OR 1=1 <other SQL injection> -- ". Now maybe you decide that because you use SQL you should encode for SQL (maybe because you didn't use parameterised statements). So now you have to mix (or decide on) SQL & HTML encoding.

突然,您的老板决定他也想要XML输出.现在,要保持模式一致,就需要对其进行编码.

Suddenly your boss decides he wants an XML output too. Now to keep your pattern consistent you need to encode for that as well.

下一个CSV-哦,不!如果文本中有引号和逗号怎么办?更多转义!

Next CSV - oh no! What if there are quotes and commas in the text? More escaping!

嘿-一个好的交互式AJAX界面怎么样?现在您可能想开始将JSON发送回浏览器,因此现在{,[等.都需要考虑在内.帮助!

Hey - how about a nice interactive, AJAX interface? Now you probably want to start sending JSON back to the browser so now {, [ etc. all need to be taken into consideration. HELP!!

因此,显然,应按给定的数据存储数据(当然要受域限制),并根据需要对输出进行适当的编码. 您的输出与您的数据不同.

So clearly, store the data as given (subject to domain constraints of course) and encode appropriate to your output at the time you need it. Your output is not the same as your data.

我希望这个答案不要太光顾.归功于其他受访者.

I hope this answer is not too patronising. Credit to the other respondents.

这篇关于在插入MySQL之前使用htmlspecialchars()很好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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