简体   繁体   English

如何转义mysql数据库名称以防止在cakephp3中进行sql注入?

[英]How to escape mysql database name to prevent sql injection in cakephp3?

I have a requirement where i have to create new mysql database with the name provided by user through form. 我有一个要求,我必须使用用户通过表单提供的名称创建新的mysql数据库。 For now i have allowed only alphanumeric characters for database name. 现在,我只允许使用alphanumeric字符作为数据库名称。

I think this alphanumeric validation on database name somehow protects me from sql injection but still i want to to prevent sql injection completely. 我认为对数据库名称的这种alphanumeric验证以某种方式保护了我免受sql injection但是我仍然想完全防止sql injection I have tried to use mysql_real_escape_string on user input but it's not escaping if user input is like this new_db_name; DROP DATABASE other_database; -- 我试图在用户输入上使用mysql_real_escape_string ,但是如果用户输入像这样的new_db_name; DROP DATABASE other_database; --它并没有转义new_db_name; DROP DATABASE other_database; -- new_db_name; DROP DATABASE other_database; -- new_db_name; DROP DATABASE other_database; -- . new_db_name; DROP DATABASE other_database; --

So how can i escape user input so that it can be used safely for databse name preventing sql injection ? 那么,如何才能逃避user input以便可以安全地将其用于防止sql injection databse name I am using cakephp3 , i have tried following code in cakephp3 which is not escaping user input like new_db_name; DROP DATABASE other_database; -- 我正在使用cakephp3,我已经尝试过在cakephp3中执行以下代码,但并未转义用户输入,例如new_db_name; DROP DATABASE other_database; -- new_db_name; DROP DATABASE other_database; --

    $db = mysql_real_escape_string($user_input);
    $rootConnection = ConnectionManager::get('rootUserConnect');

    //i)using query method
    $rootConnection->query("CREATE DATABASE $db CHARACTER SET utf8 COLLATE utf8_general_ci");

    //ii) or using execute method , it's throwing mysql syntax error
    // $rootConnection->execute("CREATE DATABASE :db CHARACTER SET utf8 COLLATE utf8_general_ci",['db' => $db]);

Thanks in advance. 提前致谢。

Use the query builder. 使用查询生成器。 You effectively ignore the ORM by what you're doing. 您通过所做的事情实际上忽略了ORM。 One of the reasons to use an ORM is to prevent SQL injections. 使用ORM的原因之一是防止SQL注入。 The ORM will take care of sanitizing the query for you. ORM将为您清理查询。

There are a few cases in which a developer can still cause the possibility of an injection. 在某些情况下,显影剂仍可能引起注入的可能性。 The manual tells you as well how to prevent that . 该手册还告诉您如何避免这种情况

You need to use the quoteIdentifier() function in the driver: 您需要在驱动程序中使用quoteIdentifier()函数:

$rootConnection = ConnectionManager::get('rootUserConnect');
$db = $rootConnection->driver()->quoteIdentifier($db);
$root->connection->execute(...);

More information about this method: http://api.cakephp.org/3.2/class-Cake.Database.Connection.html#_quoteIdentifier 有关此方法的更多信息: http : //api.cakephp.org/3.2/class-Cake.Database.Connection.html#_quoteIdentifier

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM