何时使用哪种字符串转义方法? [英] When to use which string escaping method?

查看:56
本文介绍了何时使用哪种字符串转义方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以有所有这些不同的字符串转义函数,例如 htmlentities()mysql_real_escape_string()addslashes()

但是我应该在什么情况下使用哪个?
请提供资源和意见:)

解决方案

  • addslashes()/stripslashes() 可以追溯到一个相当糟糕的想法,称为魔术行情",此后已被弃用.它会自动转义特殊字符,然后您可以使用 addslashes() 和 stripslashes() 来添加或删除它们.问题之一是您永远无法确定当前数据是否有斜线,因此您最终将未转义的数据放入 SQL 中,或者在您的网页上有额外的斜线.
  • htmlentities() 通常用于在页面上显示 HTML.如果您尝试将 <b>Something</b> 写入 HTML 页面,您只会看到 Something(即粗体的原始文本)-您不会t 看到它周围的粗体标签.使用 htmlentities('<b>Something</b>') 将代码转换为 <b>Something<b>所以在浏览器中您会看到三角括号.
  • mysql_real_escape_string() 可用于防御 MySQL 注入攻击 - 它转义字符串中的不安全字符.它不会转义其他数据类型中的任何内容,因此需要单独处理这些内容.它也不对 % 和 _ 进行编码,这在某些查询中用作通配符.

总结:

  • 如果您要编码以写入 HTML 页面,请使用 htmlentities()
  • 如果要对字符串进行编码以写入数据库,请使用 mymysql_real_escape_string()
  • 永远不要使用addslashes()

Okay, so there's all these different string-escaping functions such as htmlentities(), mysql_real_escape_string(), addslashes()

But which should I use in what situation?
Resources and opinions please :)

解决方案

  • addslashes() / stripslashes() goes back to a rather bad idea called 'Magic Quotes' which has since been deprecated. It automatically escaped special characters, and you could then use addslashes() and stripslashes() to add or remove them. One of the problems was that you were never quite sure whether the data currently had slashes or not, and thus you ended up putting unescaped data into SQL, or had extra slashes on your web page.
  • htmlentities() is used often to display HTML on the page. If you try to write <b>Something</b> to a HTML page, you will just see Something (i.e. the original text in bold) - you won't see the bold tags around it. Using htmlentities('<b>Something</b>') converts the code to <b>Something<b> so in the browser you see the triangle brackets.
  • mysql_real_escape_string() is useful for defending against MySQL injection attacks - it escapes unsafe characters in strings. It does not escape anything in other data types, and so those need to be dealt with separately. It also does not encode % and _, which are used as wildcards in some queries.

In summary:

  • If you're encoding to write to a HTML page, use htmlentities()
  • If you're encoding a string to write to a database, use mymysql_real_escape_string()
  • Never use addslashes()

这篇关于何时使用哪种字符串转义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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