简体   繁体   中英

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. For now i have allowed only alphanumeric characters for database name.

I think this alphanumeric validation on database name somehow protects me from sql injection but still i want to to prevent sql injection completely. 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; -- 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 ? 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; -- 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. One of the reasons to use an ORM is to prevent SQL injections. The ORM will take care of sanitizing the query for you.

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:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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