Is this query injection proof?

浪子不回头ぞ 提交于 2019-12-08 07:04:24

问题


I am using PDO to talk to my database, and I wonder if casting a type like this

$dbh->query("SELECT * FROM recipes WHERE id=".(int)$id);

is sufficient to prevent sql injection? In this case $id is always an integer.

I also wonder what would be a good way to prevent an injection in this kind of statement if the variable was a string.


回答1:


Yes. Casting to int prevents all the nasty SQL injection possibilities.

If the variable were a string, you should use prepared statements to pass it.

$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql);
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();



回答2:


Since you are already using PDO, a better approach will be to use:

  • Prepared Statements

This is much better:

$dbh->prepare("SELECT * FROM recipes WHERE id = ?");
$dbh->bindParam(1, (int) $id);
// more code.....



回答3:


You must escape table and field names in query:

$dbh->query("SELECT * FROM `recipes` WHERE `id=`'".(int)$id."'");



回答4:


Since you specifically cast $id to an integer, it is safe. For a string (or any other data type) you need to escape it before executing the query; have a look at PDO::quote.




回答5:


Yes, bind to a integer is enough to prevent SQL Injection if the parameter is expected as a integer.

You can also use an Automatic SQL Injection Tool to detect it.




回答6:


Careful though, in PHP (int) will convert NULL to 0.

Therefore, If you had an significant association with the ID of 0 in your application, this could trigger that value unintentionally.



来源:https://stackoverflow.com/questions/3470415/is-this-query-injection-proof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!