Is this kind of PDO query protected against SQL injection?

This question already has an answer here:

  • How can prepared statements protect from SQL injection attacks? 9 answers

  • 即使您使用过PDOSQL INjection由于您尚未参数化查询,您的代码仍然容易受到SQL INjection因此必须对查询进行参数化才能清除值。

    $userid = $_GET['id'];
    $query = "SELECT * FROM table WHERE userid=?";
    $db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
    $action = $db->prepare($query);
    $action->bindParam(1, $userid);
    $action->execute();
    

    The second statement isn't safe.

    Instead, you should do something like

    $stmt = $db->prepare('SELECT * FROM table WHERE userid=:id');
    $stmt->bindParam(':id', $userid);
    $stmt->execute();
    

    Source


    It's technically safe, as user can't affect to $userid, right? Say if I'm wrong on this.

    You are wrong with that. Session data is outside data and must be treated with caution. This is because of:

  • SessionID and SessionName are given with the request directly. These values can be easily manipulated so that some different data is being put into the memory of your application.
  • Persistence. Session data can be modified in the persistence layer so it qualifies as input data always (!).
  • You are likely expecting an integer value, so make it one:

    $userid = (int) $_SESSION['data']['id'];
    

    Especially as you directly substitute the variable into your SQL query.

    In the future don't think if it is safe. Consider to do things in a safe manner so that even if you missed something in another layer (like input through session) don't breaks the data-flow in your application.

    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
    ...
    
    $userid = (int) $_SESSION['data']['id'];
    
    ...
    
    $query = "SELECT column FROM table WHERE userid = ?";
    
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(1, $userid);
    $stmt->execute();
    
    链接地址: http://www.djcxy.com/p/93734.html

    上一篇: 我的PDO查询是否安全的SQL注入

    下一篇: 这种PDO查询是否受到SQL注入的保护?