Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4157387
  • 博文数量: 601
  • 博客积分: 15410
  • 博客等级: 上将
  • 技术积分: 6884
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-16 08:11
个人简介

独学而无友,则孤陋而寡闻!

文章分类

全部博文(601)

文章存档

2020年(1)

2018年(4)

2017年(7)

2016年(42)

2015年(25)

2014年(15)

2013年(36)

2012年(46)

2011年(117)

2010年(148)

2009年(82)

2008年(37)

2007年(41)

分类: Python/Ruby

2011-04-25 09:01:02

文介绍的是用 mysql_real_escape_string对用户提交数据进行整理处理和通过addslashes以及mysql_escape_string这3个类似的功能函数的区别。经过转义的数据可以直接插入到数据库中。

很好的说明了addslashes和mysql_real_escape_string的区别,虽然国内很多PHP coder仍在依靠addslashes防止SQL注入(包括我在内),我还是建议大家加强中文防止SQL注入的检查。addslashes的问题在于黑 客可以用0xbf27来代替单引号,而addslashes只是将0xbf27修改为0xbf5c27,成为一个有效的多字节字符,其中的0xbf5c仍 会被看作是单引号,所以addslashes无法成功拦截。

当然addslashes也不是毫无用处,它是用于单字节字符串的处理,多字节字符还是用mysql_real_escape_string吧。

另外对于php手册中get_magic_quotes_gpc的举例:
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST[‘lastname’]);
} else {
$lastname = $_POST[‘lastname’];
}
最好对magic_quotes_gpc已经开放的情况下,还是对$_POST[’lastname’]进行检查一下。

再说下mysql_real_escape_string和mysql_escape_string这2个函数的区别:
mysql_real_escape_string 必须在(PHP 4 >= 4.3.0 PHP 5)的情况下才能使用。否则只能用 mysql_escape_string ,两者的区别是:
mysql_real_escape_string 考虑到连接的当前字符集,而mysql_escape_string 不考虑。


总结一下:

addslashes() 是强行加;

mysql_real_escape_string() 会判断字符集,但是对PHP版本有要求;

mysql_escape_string不考虑连接的当前字符集。

mysql_real_escape_string()函数用于转义SQL语句中的特殊字符,该函数的语法格式如下:

  1. string mysql_real_escape_string ( string $unescaped_string
  2. [, resource $link_identifier ] )

在上述语法中涉及到的参数说明如下。

unescaped_string:未转义的字符串。

link_identifier:MySQL的连接标识符。

mysql_real_escape_string()函数不转义"%" 和 "_"这两个符号。

使用函数mysql_real_escape_string()函数的示例代码如下:

代码23-19 光盘\codes\第23章\23.4\mysql_real_escape_string.php

  1. $connection=mysql_connect("localhost","root","root")
  2. or die("连接服务器失败");
  3. $person= "Jone's and Bobo's teacher";
  4. $escaped_person= mysql_real_escape_string($person);
  5. echo $escaped_person;
  6. ?>

上面代码的输出结果如图23-18所示。

图23-18 转义后的字符



阅读(4376) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~