1 Like

PHP防止SQL Injection: Addslashes还是Mysql_real_escape_string

SQL Injection PHP防止SQL Injection: Addslashes还是Mysql real escape string
最近看了几篇关于防止SQL Injection的文章,跟大家分享一下我学到的东西。

PHP防止SQL Injection主要有两种做法,分别应用两个函数:addslashes()和mysql_real_escape_string()。早期一般用addslashes(),现在主要用mysql_real_escape_string(),这两个有什么分别呢?Alan Storm 作了以下的解释:

PHP’s mysql_real_escape_string function will, more or less, ask mysql what character(s) needs to be escaped, where the addslashses function will just add a backslash in front of and any single quote (‘), double quote (“), backslash (\) or NUL (the NULL byte) character.

我翻译如下:

PHP的mysql_real_escape_string函数会分析哪些字元需要进行处理,而addslashes则单纯对所有的单引号(‘),双引号(“),反斜线(\)和NUL字元加入反斜线。

在同一篇文章中,Waage说(翻译):

mysql_real_escape_string会为以下字元加入反斜线:
\x00, \n, \r, \, ‘, ” 和 \x1a. characters.
而addslash只为以下字元加反斜线:
‘ \ and NUL

如此看来,mysql_real_escape_string会比addslashes更安全。但如果你坚持要用addslashes的话,可以参考以下来自php5.idv.tw的程式:

function quotes($content)
{
	//if magic_quotes_gpc=Off
	if (!get_magic_quotes_gpc())
	{
		//if $content is an array
		if (is_array($content))
		{
			foreach ($content as $key=>$value)
			{
				$content[$key] = addslashes($value);
			}
		} else
		{
			//if $content is not an array
			addslashes($content);
		}
	} else
	{
		//if magic_quotes_gpc=On do nothing
	}
	return $content;
}

这个程式首先会检查magic_quotes_gpc是否开启,由于magic_quotes_gpc的功能和addslashes()重覆,所以,我们只在magic_quotes_gpc关闭时才做addslashes()处理。进行addslashes()时,再分别处理数组与非数组数据。

当然,你也可以参照以上的程式,做一个mysql_real_escape_string()的版本。以下是我的版本:

function quotes($content)
{
	//if $content is an array
	if (is_array($content))
	{
		foreach ($content as $key=>$value)
		{
			$content[$key] = mysql_real_escape_string($value);
		}
	} else
	{
		//if $content is not an array
		mysql_real_escape_string($content);
	}
	return $content;
}

几乎是一样,只是除去了magic_quotes_gpc的判断,再将addslashes换成mysql_real_escape_string。你可以参考以下例子使用这个函数:

$name = quotes($_POST['user']);
$password = quotes($_POST['password']);

欢迎到我们的论坛发表你的看法

关于 Zack

喜欢WordPress,WordPress主题设计学习中; 关注网络,特别是Web2.0的发展.英文网志:http://ZackLive.com
本篇发表于 网页设计 并标签为 , , , , , 。将永久炼结加入书签。

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

PHP防止SQL Injection: Addslashes还是Mysql_real_escape_string 有 3 则回应

  1. 通告: Zack Live

  2. 通告: Zack Live

  3. limon 说道:

    foreach 里应该递归 $value可能还是array

留下评论

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>