当magic_quotes_gpc开启时,是否有必要使用mysql_real_escape_string()? [英] Is it necessary to use mysql_real_escape_string(), when magic_quotes_gpc is on?
问题描述
要防止SQL注入,在magic_quotes_gpc
启用时是否必须使用mysql_real_escape_string()
?
To prevent SQL injection, is it necessary to use mysql_real_escape_string()
, when magic_quotes_gpc
is on?
推荐答案
对于一些罕见的编码,
当然,mysql_real_escape_string()
仅在带引号的字符串中有效.所以,如果你这样做
For some rare encodings, such as GBk - yes.
But you should revert it not for this reason. Magic quotes should be turned off anyway (and will be in the next PHP version). So, mysql_real_escape_string() is the only escape function is left. Note that it is not sql injection prevention function. Many many people don't understand this point: it's just a part of syntax. It must be used not to "protect" anything, but to assemble syntactically correct SQL query. And must be used every time you build your query, no matter where data come from. Sure it will protect you from SQL injections too, as a side effect.
Of course, mysql_real_escape_string()
works only within quoted strings. So, if you do
$num=mysql_real_escape_string($num);
$sql="SELECT INTO table SET data=$num"; /BAD!!!
它不会保护任何东西. 如果要使用不带引号的数字,则必须将其强制转换为正确的类型,例如:
It will protect nothing. If you going to use numbers unquoted, it must be cast to the proper type obligatory, like this:
$num=intval($num);
$sql="SELECT INTO table SET data=$num"; /GOOD
- 请记住,mo make
mysql_real_escape_string()
会按预期工作,应设置正确的客户端编码,并且可能仅使用mysql_set_charset()
功能,SET NAMES查询不会设置该设置. /li>- Keep in mind that mo make
mysql_real_escape_string()
works as intended, proper client encoding should be set, and it is possible only withmysql_set_charset()
function, SET NAMES query will not set that.
If you want to get rid of all these complexities, you can use prepared statements, though you will need to switch your mysql driver to mysqli or PDO.
请注意,没有任何正确的语法或准备好的语句将无法帮助您查询除文字以外的部分.您无法转义标识符或运算符.如果您碰巧动态使用这些部分,则必须在脚本中对它们进行硬编码,如下所示(对于ORDER BY子句):
Please note that no proper syntax nor prepared statements would not help you with query parts other than literals. You can't escape Identifiers or operators. If you happen to use these parts dynamically, they must be hardcoded in your script, like this (for the ORDER BY clause):
$orders=array("name","price","qty"); $key=array_search($_GET['sort'],$orders)); $orderby=$orders[$key]; $query="SELECT * FROM `table` ORDER BY $orderby";
或这个(WHERE子句)
or this (WHERE clause)
$w=array(); if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'"; if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'"; if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'"; if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where=''; $query="select * from table $where";
这篇关于当magic_quotes_gpc开启时,是否有必要使用mysql_real_escape_string()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Keep in mind that mo make