如何在我的login.php页面上获得“用户名或密码错误”消息?

I'm trying to show the standard "Invalid Username or Password" message on my login page. I've found other questions and answers on stackoverflow such as: How to display login error message on the same page in a php based system?

我已经根据找到的一些答案实施了代码,但我的loginscript.php可能会变得很复杂,以致代码无法正常工作。

当我访问该页面并为一个已知的良好用户使用一个已知的错误密码时,它只会重定向到login.php页面,而不会显示“无效的用户名或密码”消息。

相关的loginscript.php代码:

if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
  // Bind parameters
  $stmt->bind_param('s', $_POST['username']);
  $stmt->execute();
  // Store results for account verification
  $stmt->store_result();

if ($stmt->num_rows > 0) {
  $stmt->bind_result($id, $password);
  $stmt->fetch();
  // Account exists, new to check the password.
  // Note: remember to use password_hash in your registration file to store hashed passwords
  if (password_verify($_POST['password'], $password)) {
    // Successful verification, user logged in.
    // Create Session
    session_regenerate_id();
    $_SESSION['loggedin'] = TRUE;
    $_SESSION['name'] = $_POST['username'];
    $_SESSION['id'] = $id;
    $_SESSION['session_start'] = time();

    if (isset($_SESSION['id'])) {
      if(!isLoginSessionExpired()) {
        header("Location: /index.php");
      } else {
        header("Location: logout.php?session_expired=1");
      }
    }
  } else {
    $_SESSION['error'] = "Invalid username or password";
    header("Location: login.php");
  }
} else {
    $_SESSION['error'] = "Invalid username or password";
    header("Location: login.php");
}

  $stmt->close();
}

相关的login.php代码:

        <form class="box" action="loginscript.php" method="post">
            <h1>Login</h1>
            <input type="text" name="username" placeholder="Username">
            <input type="password" name="password" placeholder="Password">
            <input type="submit" value="Login">
            <?php if(isset($_SESSION['error'])) {
        $error = $_SESSION['error'];
        ?>
                <div class="message">
                    <span><?php $_SESSION['error']; ?></span>
                </div>
            <?php } ?>
            <img src="images/logo.png" alt="Logo" height="50">
        </form>

任何建议或指向我要出错的地方,将不胜感激。

评论
  • 心碎~囧
    心碎~囧 回复

    为了在这种情况下输出变量,您需要回显它:

    <?php echo $_SESSION['error']; ?>
    
  • 毒心術
    毒心術 回复

    You can't usefully use $_SESSION unless you call session_start() (before any output is sent) in any script you use it in.

    您还必须输出变量的内容,而不仅仅是提及它:

    <span><?php echo $_SESSION['error']; ?></span>