如何防止在手动创建的查询中注入SQL? [英] How to prevent SQL injections in manually created queries?

查看:59
本文介绍了如何防止在手动创建的查询中注入SQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是cakephp,据我所知,下面的查询有SQL注入。但问题是如何在相同的查询中解决这个问题。我不想用其他方法。请不要取消投票

Search->query("select * from subcategories where subcat_name like '%".$_GET['searchkey']."%' and subcat_status='active' ");

推荐答案

我不想使用其他方法

您应该使用任何提供所需功能的方法,而不是您喜欢的方法!

此外,您永远不应该在CakePHP中直接访问超全局变量,这只会给您带来麻烦,尤其是在单元测试中。使用请求对象提供的适当的抽象方法,即CakeRequest::query()

Cookbook > Controllers > Request and Response objects > Accessing Querystring parameters


使用预准备语句

话虽如此,请使用预准备语句,方法是传递要绑定到Model::query()的第二个参数的值:

$result = $this->Search->query(
    "select * from subcategories where subcat_name like ? and subcat_status='active'",
    array('%' . $this->request->query('searchkey') . '%')
);

API > Model::query()

或使用DboSource::fetchAll(),它也接受参数作为第二个参数:

$db = $this->Search->getDataSource();
$result = $db->fetchAll(
    "select * from subcategories where subcat_name like ? and subcat_status='active'",
    array('%' . $this->request->query('searchkey') . '%')
);

手动退出

为了完整性,也可以通过DboSource::value()手动转义值,但应避免不惜一切代价以这种方式构建查询字符串,因为一个小错误最终可能导致插入未转义的值,从而产生可能的SQL注入漏洞:

$searchkey = $this->request->query('searchkey');

$db = $this->Search->getDataSource();
$value = $db->value('%' . $searchkey . '%', 'string');

$result = $this->Search->query(
    "select * from subcategories where subcat_name like $value and subcat_status='active'"
);

API > DboSource::value()

这篇关于如何防止在手动创建的查询中注入SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆