donglanfu5831 2013-01-14 17:03
浏览 41
已采纳

MySQL注入查询

I'm familiar with prepared statements and I know that they are best practice when it comes to protecting against MySQL injection. But I'm wondering how this PHP/MySQL statement could be at risk of an injection attack:

$result = mysqli_query($db,"SELECT name FROM users WHERE id = '".$_POST['name']."';");

It seems to me like the input from the user would be contained inside the single quotes. Can you execute more than one query in one mysqli_query statement?

Also, is making the above safe just as easy as this...

$result = mysqli_query($db,"SELECT name FROM users WHERE id = '".mysqli_real_escape_string($_POST['name'])."';");
  • 写回答

5条回答 默认 最新

  • dqysi86208 2013-01-14 17:22
    关注

    It seems to me like the input from the user would be contained inside the single quotes

    It would unless you include single quotes in the posted name, which would allow you to break out of the quotes. Example, post the name as:

    ' or 1 or '
    

    The WHERE clause becomes:

    WHERE id = '' or 1 or '';
    

    This would match and retrieve all rows in the table because of the or 1 part. As you can see, it breaks out of the quotes to inject some SQL, then it goes back into the quotes to make the query valid.

    Can you execute more than one query in one mysqli_query statement?

    No, but if it was executed with mysqli_multi_query then yes you could add multiple queries on to the end.

    is making the above safe just as easy as mysqli_real_escape_string?

    Generally yes but a Prepared Statement would be better. Using escaping, the WHERE clause would become (using my example above):

    WHERE id = '\' or 1 or \'';
    

    This is no longer vulnerable because the quotes can't be broken out of, and would only match rows if the name literally matches ' or 1 or ' which is obviously unlikely.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入