我正在使用 PHP 和 MySQL 创建一个 Web 应用程序。我设置了注册/登录页面。我已通过该应用程序注册了多个帐户,并且看到消息称帐户已成功创建,但当我尝试登录时,它失败并显示“用户名或密码无效”错误消息。 当我转到 PHPMyAdmin 时,我可以看到所有用户帐户都存在于用户表中,并且我可以看到用户名及其密码(后者采用散列格式)。所以我不明白为什么我无法登录。
这是我的登录表单(在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_error=true HTTP/1.1”200 1230“http://localhost/index.php?registered=true”“Mozilla/5.0(X11;Ubuntu; Linux x86_64;rv:61.0) Gecko/20100101 Firefox/61.0"
最佳答案
使用$stmt->execute()
后,您需要use $stmt->fetch()
to retrieve 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;
}
关于php - 创建 PHP/MySQL 应用程序 - 所有登录尝试均失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027092/