我应该同时使用htmlspecialchars和mysql_real_escape_string吗 [英] Should I use htmlspecialchars and mysql_real_escape_string both

查看:54
本文介绍了我应该同时使用htmlspecialchars和mysql_real_escape_string吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已让用户提供一些信息. (姓名,出生日期等).然后我必须将这些值放入数据库.我应该使用mysql_real_escape_string来防止mysql注入和htmlspecialchars来处理html标记,还是它们之一可以完成工作?

如果我应该使用其中之一,那么应该使用哪一个?
如果我应该同时使用第一个和最后一个?

解决方案

如果期望用户输入需要翻译的某些字符,则可以使用htmlspecialchars否则就没有必要.

但是您可以同时使用这两种方法都将为您带来好处.

首先使用htmlspecialchars,然后使用mysql_real_escape_string


在插入或更新MySQL数据库时使用mysql_real_escape_string.

要在HTML页面上显示内容时,请使用htmlspecialchars.

像这样使用它们意味着您将输入的内容存储在数据库中,但是您可以根据您将如何显示数据(HTML,LaTeX,纯文本等)使用不同的转义功能

我建​​议您在预期来自用户的输入具有特殊html字符(例如<,&,>)的情况下使用htmlspecialchars.标志,或其他在html中具有特殊含义的字符.但是,如果只希望用户仅处理文本,则可能不是必需的.

另一方面,必须使用mysql_real_escape_string来控制用户在数据库中存储的内容并防止sql注入. mysql_real_escape_string确保在用户输入的内容存储在数据库中之前先对其进行处理,并对sql引擎具有特殊含义的字符进行正确的转义.

如果您打算同时使用两者,请先使用htmlspecialchars,然后使用mysql_real_escape_string,而不是反之.


I have let the user to give some information. (name, date of birth etc). then I have to put these values to database. Should I use mysql_real_escape_string to prevent the mysql injection and htmlspecialchars to handle the html tags both or one of them can do the work?

If I should use one of them, then which one?
If I should use both then which one first and which one last?

解决方案

You can user htmlspecialchars if you are expecting the user to enter certain characters that need to be translated else it wouldn''t be necessary.

But you can use both it will be to your advantage.

use htmlspecialchars first followed by mysql_real_escape_string


Use mysql_real_escape_string when you are inserting into or updating a MySQL database.

Use htmlspecialchars when you are going to display something on an HTML page.

Using them like this means that you will store the input in the database as entered, but you can then use a different escape function depending on how you are going to display the data (HTML, LaTeX, plain text, etc.)


I would recommend you use htmlspecialchars when the input from the user is expected to have special html characters such as the <, &, > signs, or any other characters that have special meaning in html. However, if you only expect your users to process only text, then it might not be a requirement.

On the other hand, mysql_real_escape_string is necessary to control what the users are storing in the database and to prevent sql injection. mysql_real_escape_string ensures that whatever the user enters is processed first before it is stored in the database and characters with special meaning to the sql engine is properly escaped.

If you plan to use both, please use the htmlspecialchars first, and then the mysql_real_escape_string follows, and not vice-versa.


这篇关于我应该同时使用htmlspecialchars和mysql_real_escape_string吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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