"Cant process the request",处理基本的参数化查询

"Cant process the request", dealing with basic parameterized queries

我正在尝试我在网上找到的东西(对此非常陌生)并且 none 有效。这是一个随机的科学项目,我决定了解更多,但我仍停留在 "procedures" 的第 2 部分。 https://www.sciencebuddies.org/science-fair-projects/project-ideas/Cyber_p008/cybersecurity/sql-injection#procedure

我看过视频,但它们只包含 user_ID 而不是用户名和密码。注意:只有处理 login.php 的代码才会导致问题。

<?php
include("global.php");
include("db.php");

session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  // username and password are sent in the form 

  $username = $_POST['username'];
  $password = $_POST['password']; 

  // Check if the username and password exist in the database

  $sql = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
  $stmt = msqli_stmt_init($db);
  if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "SQL Statement Failed";
  } else {
      mysqli_stmt_bind_param($stmt, "ss", $username, $password );
  mysqli_stmt_execute($stmt);
   $result = mysqli_stmt_get_result($stmt);
   $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

   $count = mysqli_num_rows($result);}
  // If username and password matched then there is one row in the result

  if ($count != 0) {
     $_SESSION['login_user'] = strtolower($username);

     header("location: search.php");
  }
  else {
     $error = "Your Username or Password is invalid";
  }

} ?>

它本应阻止基本的“'or''='”注入攻击,但它决定不完全起作用。

如果您使用查询参数——这绝对是个好主意——您必须在查询中保留占位符。使用 ? 作为占位符。

像这样:

$sql = "SELECT username FROM users WHERE username = ? AND password = ?";

您稍后将变量绑定到这些参数。您必须绑定与参数占位符数量相同的变量。

您遇到了您描述的错误,因为您试图将变量绑定到没有参数占位符的查询。