数据库查询和报价

时间:2010-08-21 19:56:57

标签: php security url quotes

如果我使用http://site.com/index.php?page=45,一切看起来都不错(想要加载页面)。

但是,当我浏览http://site.com/index.php?page=45'http://site.com/index.php?page=45"时(在数字后添加引号)页面会打印错误:

Unhandled Exception (Debug)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'
 ORDER BY datePub DESC
 LIMIT 10' at line 9
SELECT *, date_format(date, '%d') AS day, date_format(date, '%m') AS month, date_format(date, '%Y') AS year FRO...
// and paths to my scripts
对于黑客来说,这就像比萨啤酒一样。

如何过滤不需要的符号(如引号),这样页面就不会显示我的数据库查询(可能是我自己的错误文本)?

我已关闭错误报告,但它不是解决方案(无法在任何地方使用它)。

3 个答案:

答案 0 :(得分:2)

$page = (int) $_GET['page'];

$page = preg_replace('~[^0-9]~','',$_GET['page']);

答案 1 :(得分:0)

输入page变量:

可能的解决方案1:

$page = (int) $_GET['page'];

测试用例:

$str = '45"';
echo (int) $str;

<强>结果:

45

可能的解决方案2:

或者您可以使用is_numericctype_digit函数拒绝此类无效值:

if (!ctype_digit($_GET['page'])){
   die('Invalid page value !!');
}
else{
 // continue with the query...
}

可能的解决方案3:

您可以使用此正则表达式删除不需要的字符:

$page = preg_replace("/[^0-9]+/", "", $_GET['page']);

更新

对于文本,您应该使用mysql_real_escape_string函数。

答案 2 :(得分:0)

使用(int)$ _ GET ['page']。如果这不起作用,您将抓取url,这意味着您需要使用正则表达式。我不明白你为什么要抓取这个网址,所以你应该没问题。