是否可以设置URL的参数查询?

时间:2017-10-04 04:30:52

标签: sql parameterized-query

我想知道开发人员可以设置url 的参数化查询来缓解SQL注入漏洞吗?

例如:

https://example.com/somefile.php?id=1

开发人员如何为此进行参数化查询?就像他们在应用程序中的参数中这样做了吗?

2 个答案:

答案 0 :(得分:0)

是的,你可以做到。参数化查询很简单,它会强制您事先定义SQL查询,并在查询中使用占位符作为用户提供的变量。然后,您可以在定义SQL语句后将每个参数传递给查询,从而允许数据库区分SQL命令和用户输入的数据。如果攻击者输入了SQL命令,则参数化查询会将这些命令视为不受信任的输入,并且注入的SQL命令将永远不会执行。请注意下面提供的示例,以便更好地理解。

if (isset($_GET['id'])){
  $id = $_GET['id'];
  /**
   * Validate data before it enters the database. In this case, we need to check that
   * the value of the 'id' GET parameter is numeric
   */
   if ( is_numeric($id) == true){
    try{ 
      $dbh = new PDO('mysql:host=localhost;dbname=sql_injection_example', 'dbuser', 'dbpasswd');

      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      /**
       * Before executing our SQL statement, we need to prepare it by 'binding' parameters.
       * We will bind our validated user input (in this case, it's the value of $id) to our
       * SQL statement before sending it to the database server.
       *
       * This fixes the SQL injection vulnerability.
       */
      $q = "SELECT username 
          FROM users
          WHERE id = :id";
      // Prepare the SQL query
      $sth = $dbh->prepare($q);
      // Bind parameters to statement variables
      $sth->bindParam(':id', $id);
      // Execute statement
      $sth->execute();

      $sth->setFetchMode(PDO::FETCH_ASSOC);
      // Fetch result
      $result = $sth->fetchColumn();
      /**
       * HTML encode our result using htmlentities() to prevent stored XSS and print the
       * result to the page
       */
      print( htmlentities($result) );

      $dbh = null;
    }
    catch(PDOException $e){
      /**
       * You can log PDO exceptions to PHP's system logger, using the Operating System's
       * system logging mechanism
       *
       * For more logging options visit http://php.net/manual/en/function.error-log.php
       */
      error_log('PDOException - ' . $e->getMessage(), 0);
      /**
       * Stop executing, return an 'Internal Server Error' HTTP status code (500),
       * and display an error
       */
      http_response_code(500);
      die('Error establishing connection with database');
    }
   } else{
    /**
     * If the value of the 'id' GET parameter is not numeric, stop executing, return
     * a 'Bad request' HTTP status code (400), and display an error
     */
    http_response_code(400);
    die('Error processing bad or malformed request');
   }
}
?>

答案 1 :(得分:0)

问题不在URL中,而是如何使用稍后在URL中传递的参数。

最好的方法是使用绑定变量:

你也可以'治疗'或'消毒''通过转义和/或删除可疑数据来获取您的参数。对于容易出错的人来说,这通常是一件非常棘手的事情。因此绑定变量使用起来更简单,更安全。