如何防止我的代码和sql体系结构从sql注入。
我正在用PHP进行编码..
我有某种形式的登录名。我读了一些SQL注入查询
string sql = "SELECT * FROM table_name WHERE smth='" + UserInput + "'";
ExecuteSql(sql);
SELECT fieldlist
FROM table
WHERE field = 'steve@unixwiz.net'';
我知道发生sql注入是因为我们的编码错误和从数据库检索数据的查询错误。
我也使用cakephp框架进行编码,并且我知道在cakephp中,sql注入非常困难,因为它可以清理查询。
我为此得到了这些信息:-
CakePHP already protects you against SQL Injection if you use CakePHP's ORM methods (such as find() and save()) and proper array notation (ie. array('field' => $value)) instead of raw SQL. For sanitization against XSS its generally better to save raw HTML in database without modification and sanitize at the time of output/display.
有人会为此指导我吗?
谢谢 !!
最佳答案
@Learner在谈论CakePHP框架中的查询,而不是一般的注入(尽管了解这一点也很重要)。
当CakePHP说
如果您使用CakePHP的ORM方法(例如find()和save())和正确的数组表示法(即array('field'=> $ value))而不是原始SQL,CakePHP已经为您提供了防止SQL注入的保护。为了对XSS进行清理,通常最好将原始HTML保存在数据库中而不进行修改,并在输出/显示时进行清理。
您需要做的就是它所说的。当您对数据库运行任意查询时,它不能保护您-不能,因为您绕过CakePHP。当它确实保护您时,查询将在框架中运行:
$result = $this->Article->find(
'first', array(
'conditions' => array('Article.id' => $articleIDtoFind)));
在此示例中,
$articleIDtoFind
的来源无关紧要,查询是安全的。 (如果到处都是垃圾,那可能就行不通了)