简体   繁体   中英

Avoid sql injection in yii2

How to filter query parameters before inserting them into table to prevent sql injection?

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:

$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.

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