简体   繁体   English

避免在yii2中注入sql

[英]Avoid sql injection in yii2

How to filter query parameters before inserting them into table to prevent sql injection? 如何在将查询参数插入表之前过滤查询参数以防止sql注入?

Have such code: 有这样的代码:

$QueryParams = Yii::$app->request->getQueryParams();
$model = new Accounts();
$model->attributes = $QueryParams;
$connection->createCommand()->insert('accounts', $model->attributes)->execute();

Is this safe approach? 这是安全的方法吗?

The approach is safe, but there is a better one: 这种方法是安全的,但有一个更好的方法:

$model = new Accounts();

if ($model->load(Yii::$app->request->get()) && $model->save()) {
    // 'when the model is saved' logic here
}

// other code

This basically does, what the posted code does, but includes model validation, is shorter, and is easier to understand. 这基本上做了,发布的代码做了什么,但包括模型验证,更短,更容易理解。

The approach is safe. 这种方法很安全。 But, if the Accounts class is an ActiveRecord class (extends it), then you can simplify your code: 但是,如果Accounts类是ActiveRecord类(扩展它),那么您可以简化代码:

$model->load(Yii::$app->request->get());
$model->save();

It's equivalent to: 它相当于:

$connection->createCommand()->insert('accounts', $model->attributes)->execute();

Which is less intuitive, and may even have compatibility problems if you are using a different kind of database. 哪个不太直观,如果您使用的是其他类型的数据库,甚至可能存在兼容性问题。

Also, sometimes you need raw queries. 此外,有时您需要原始查询。 In this case it's preferred to use prepared statements : 在这种情况下,最好使用预准备语句

$result = $connection
    ->createCommand('SELECT id FROM accounts WHERE name=:name')
    ->bindValues([':name' => $name])
    ->queryColumn();

There is a good Yii2 security best practices guide on GitHub. GitHub上有一个很好的Yii2安全最佳实践指南。

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

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