我如何添加mysql_real_escape_string():这个?

时间:2012-04-07 19:50:58

标签: php security

以下是代码:

  //check if the starting row variable was passed in the URL or not
  if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {
 //we give the value of the starting row to 0 because nothing was found in URL
  $startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)mysql_real_escape_string($_GET['pg']);
}

每当我尝试添加mysql_real_escape_string();在.isset中的$ _GET ['pg'),代码没有执行,我没有得到任何错误消息。

3 个答案:

答案 0 :(得分:2)

不要将pg值转换为int。相反,请验证它是否包含整数值,或者不执行查询。如果您没有计划执行查询(我们无法查看),那么mysql_real_escape_string()完全是错误的工具,因为它需要连接。

适当的做法是验证$_GET['pg']的内容是一个整数,而不是逃避它。

由于is_numeric()将为非整数实数返回TRUE,因此我倾向于使用ctype_digit()来验证正整数。如果您还需要负整数的可能性,则可以使用ctype_digit(abs($_GET['pg']))

if (!isset($_GET['pg']) or !ctype_digit($_GET['pg'])) {
   // it wasn't an integer
   // initialize to your default value
}
else {
  // $_GET['pg'] *has to be a valid int* or we wouldn't have entered the else block
  // no need to escape or further process it - it's safe to use
}

答案 1 :(得分:1)

您想要一个0或更大的整数值;如果输入无效,则为0:

$startrow = max(0, isset($_GET['pg']) ? $_GET['pg'] : 0);

整数值不需要mysql_real_escape_string()。根据您的编码风格,这也可以在PHP中使用:

$startrow = max(0, @$_GET['pg']);

如果您使用的是PHP 5.4,它的表现就相当不错。

答案 2 :(得分:0)

mysql_real_escape_string需要连接数据库(第二个参数),如果未提供,将使用上次打开的连接 - 请参阅:

http://php.net/manual/en/function.mysql-real-escape-string.php

可能是在代码的这一点上没有创建与数据库的连接?在这种情况下,您应该看到一个警告(检查您的php配置是否允许替换警告)

相关问题