if(isset($_POST['submit'])){
$content=$_POST['content'];
if(!get_magic_quotes_gpc()){
$content=addslashes($content);
}
$content=$db->real_escape_string($content);
}
?>
<form action="" method="post">
<input type='text' name='content'>
<input type='submit' name='submit' value='提交'>
</form>如上面代码所示,有二种方式可以转义有注入风险的特殊字符,一个是addslashes(),另一个是real_escape_string(),不知道在具体的使用过程,应该使用那一种合适,二者之间的不同之处在那里?
$content=$_POST['content'];
if(!get_magic_quotes_gpc()){
$content=addslashes($content);
}
$content=$db->real_escape_string($content);
}
?>
<form action="" method="post">
<input type='text' name='content'>
<input type='submit' name='submit' value='提交'>
</form>如上面代码所示,有二种方式可以转义有注入风险的特殊字符,一个是addslashes(),另一个是real_escape_string(),不知道在具体的使用过程,应该使用那一种合适,二者之间的不同之处在那里?
mysql_real_escape_string()会转义\x00, \n, \r, \, ', "和\x1a字符。
推荐使用后者。
mysql_real_escape_string
(PHP 4 >= 4.3.0, PHP 5)mysql_real_escape_string -- 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集
说明
string mysql_real_escape_string ( string unescaped_string [, resource link_identifier] )
本函数将 unescaped_string 中的特殊字符转义,并计及连接的当前字符集,因此可以安全用于 mysql_query()。 注: mysql_real_escape_string() 并不转义 % 和 _。 例子 1. mysql_real_escape_string() 例子<?php
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?> 以上例子将产生如下输出: Escaped string: Zak\'s and Derick\'s Laptop
[code=PHP]
if(get_magic_quotes_gpc())
{
$data=stripslashes($data);
}
[/code]
单引号(’)、双引号(”)、反斜线(\)与 NUL(NULL 字符)等字符都会被加上反斜线。这些转义是必须的,如果这个选项为off,那么我们就必须调用addslashes这个函数来为字符串增加转义。正是因为这个选项必须为On,但是又让用户进行配置的矛盾,在PHP6中删除了这个选项,一切的编程都需要在 magic_quotes_gpc=Off下进行了。在这样的环境下如果不对用户的数据进行转义,后果不仅仅是程序错误而已了。同样的会引起数据库被注入 攻击的危险。所以从现在开始大家都不要再依赖这个设置为On了,以免有一天你的服务器需要更新到PHP6而导致你的程序不能正常工作。当magic_quotes_gpc=On的时候,函数get_magic_quotes_gpc()就会返回1
当magic_quotes_gpc=Off的时候,函数get_magic_quotes_gpc()就会返回0因此可以看出这个get_magic_quotes_gpc()函数的作用就是得到环境变量magic_quotes_gpc的值。既然在PHP6中删除了magic_quotes_gpc这个选项,那么在PHP6中这个函数我想也已经不复存在了。