如何在 Yii 1.1 中保护原始 sql CDbCriteria 条件(反 sql 注入)?
How can I secure raw sql CDbCriteria condition (anti sql injection) in Yii 1.1?
我正在处理 Yii 1.1 应用程序。
部分搜索方法使用 CDbCriteria
和原始 sql。
我想知道如何才能继续使用原始 sql 代码并使其更安全地免受 sql 注入?
这是一个代码示例:
if (!empty($this->textToSearch)) {
$text_condition = <<<EOC
(
topic LIKE "%{$this->textToSearch}%" OR
main LIKE "%{$this->textToSearch}%" OR
)
EOC;
$criteria->addCondition($text_condition);
}
有什么建议吗?
您应该使用params 传递不受信任的数据进行查询。请注意 %
、_
和 \
字符在 SQL 查询中具有特殊含义,因此您也需要对其进行转义。
$criteria = new CDbCriteria();
if (!empty($this->textToSearch)) {
$text_condition = <<<EOC
(
topic LIKE :text_to_search OR
main LIKE :text_to_search
)
EOC;
$criteria->addCondition($text_condition);
$textToSearch = strtr($this->textToSearch, [
'%' => '\%',
'_' => '\_',
'\' => '\\',
]);
$criteria->params[':text_to_search'] = "%{$textToSearch}%";
}
我正在处理 Yii 1.1 应用程序。
部分搜索方法使用 CDbCriteria
和原始 sql。
我想知道如何才能继续使用原始 sql 代码并使其更安全地免受 sql 注入?
这是一个代码示例:
if (!empty($this->textToSearch)) {
$text_condition = <<<EOC
(
topic LIKE "%{$this->textToSearch}%" OR
main LIKE "%{$this->textToSearch}%" OR
)
EOC;
$criteria->addCondition($text_condition);
}
有什么建议吗?
您应该使用params 传递不受信任的数据进行查询。请注意 %
、_
和 \
字符在 SQL 查询中具有特殊含义,因此您也需要对其进行转义。
$criteria = new CDbCriteria();
if (!empty($this->textToSearch)) {
$text_condition = <<<EOC
(
topic LIKE :text_to_search OR
main LIKE :text_to_search
)
EOC;
$criteria->addCondition($text_condition);
$textToSearch = strtr($this->textToSearch, [
'%' => '\%',
'_' => '\_',
'\' => '\\',
]);
$criteria->params[':text_to_search'] = "%{$textToSearch}%";
}