所有登录尝试都失败

uyto3xhc  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(355)

我正在用php和mysql创建一个web应用程序。我有一个注册/登录页面设置。我已经通过该应用程序注册了几个帐户,我看到一条消息说帐户已经成功创建,但是当我尝试登录时,它失败了,并显示一条“无效用户名或密码”的错误消息。当我转到phpmyadmin时,我可以看到所有用户帐户都存在于users表中,并且可以看到用户名和密码(后者是散列格式)。所以我不明白为什么我不能登录。
这是我的登录表单(在index.php中):

<!-- login form -->
    <form method="post" action="php/login.php">
      <div class="form-group">
        <input class="form-control" type="text" name="username" placeholder="Username" required>
      </div>

      <div class="form-group">
        <input class="form-control" type="password" name="password" placeholder="Password" required>
      </div>

      <div class="form-group">
        <input class="btn btn-primary" type="submit" name="login" value="Login">
      </div>
    </form>
 <!-- ./login form -->

这是login.php:

<?php
  require_once "../functions.php";

  db_connect();

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

  $statement = $conn->prepare($sql);
  $statement->bind_param('s', $_POST['username']);
  $statement->execute();
  $statement->store_result();
  $statement->bind_result($id, $username, $password);
  $statement->fetch();

  if ($statement->execute()) {
    if(password_verify($_POST['password'], $password)) {
      $_SESSION['user_id'] = $id;
      $_SESSION['user_username'] = $username;
      redirect_to("/home.php");
    } else {
      redirect_to("/index.php?login_error=true");
    }
  } else {
    echo "Error: " . $conn->error;
  }
  ?>

这是错误消息的代码(在index.php中):

<?php if(isset($_GET['login_error'])): ?>
<div class="alert alert-danger">
  <p>Invalid username or password!</p>
</div>

在apache access.log中,我可以看到:127.0.0.1---[26/aug/2018:14:54:07+0100]“get/index.php?login\u error=true http/1.1”200 1230http://localhost/index.php?registered=true“”mozilla/5.0(x11;乌班图;linux x86_;rv:61.0)壁虎/20100101火狐/61.0“

6za6bjd0

6za6bjd01#

使用后 $stmt->execute() 你需要使用 $stmt->fetch() 从数据库检索结果集 SELECT 查询。
尝试以下操作:

if ($statement->execute()) {
  while ($statement->fetch()) {
      if(password_verify($_POST['password'], $password)) {
        $_SESSION['user_id'] = $id;
        $_SESSION['user_username'] = $username;
        redirect_to("/home.php");
      }
  }
  redirect_to("/index.php?login_error=true");
} else {
  echo "Error: " . $conn->error;
}
oogrdqng

oogrdqng2#

我设法找到了问题的起因。最初在数据库中创建users表时,我将password字段的最大字符数设置为40。我没有考虑到密码的散列版本可能超过40个字符。一旦我将限制从40增加到一个更高的值并创建了一个新帐户,我就能够成功地登录。

相关问题