gpt4 book ai didi

PHP 登录表单错误

转载 作者:行者123 更新时间:2023-11-29 12:04:24 25 4
gpt4 key购买 nike

我正在尝试通过创建一个小型登录表单来学习 PHP。我有两个错误。首先,当我登录时,我只能登录一个用户,即我在数据库中 ID 为 1 的用户。我总共有 3 个用户,但无法登录其他用户。其次,我希望在登录时无法访问登录表单。

我已连接到数据库。

登录表单:

<!DOCTYPE html>
<?php

session_start();

$username = $_POST['username'];
$password = $_POST['password'];
$securePassword = md5($password);

{ // Select table(s)
$tUsers_Select = "SELECT user_id, username, password FROM users";
$tUsers_Select_Query = mysqli_query($dbConnect, $tUsers_Select);
}
$row = mysqli_fetch_array($tUsers_Select_Query);

$dbusername = $row['username'];
$dbpassword = $row['password'];

if ($username == $dbusername AND $securePassword == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("Location: home.php");
} else {
echo "Incorrect name or password";
}

?>
<div id="main-content">
<div class="welcome-msg">
<h1 class="huge">Welcome!</h1>
<h3 class="medium">Please sign in</h3>

<form id="login-form" action="/lr/index.php" method="post">
<label for="username">Username</label>
<input type="text" name="username" id="username">

<label for="password">Password</label>
<input type="password" name="password" id="password">

<button type="submit" name="submit">Log in</button>
</form>

</div>
</div>

</body>

主页:

<!DOCTYPE html>
<html>
<?php

session_start();


{ // Select table(s)
$tUsers_Select = "SELECT * FROM users";
$tUsers_Select_Query = mysqli_query($dbConnect, $tUsers_Select);
}

if (isset($_SESSION['username'])) {


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

// echo $username."<br />";
// echo $password."<br />";
// echo $securePassword."<br />";

} else {
header(
"Location: /lr/index.php"
);
}

?>

<div id="main-content">
<h1 class="huge">Welcome back, <?php echo $username ?>!</h1>
<a href="/lr/logout.php">Logout</a>
</div>


</body>

退出:

<!DOCTYPE html>
<?php

session_start();
session_destroy();

?>
<div id="main-content">
<div class="welcome-msg">
<h1 class="huge">Bye-Bye!</h1>
</div>
</div>

</body>

如果您需要更多详细信息,请评论。

最佳答案

首先,您将获取所有用户,然后首先从中获取用户,然后检查您的输入。这是错误的,并且将始终使用表的第一条记录检查您的输入。另外,使用crypt()来散列密码会更好。
相反,更改您的查询以使用您拥有的信息获取用户:

$securePassword = crypt($password, $password);
$stmt = mysqli_prepare("SELECT user_id, username, password FROM users WHERE username=? AND password=?");
$stmt->bind_param( "ss", $username, $securePassword);
$stmt->execute();

if($stmt->num_rows === 1)
{
$_SESSION['username'] = $username;
//$_SESSION['password'] = $password; You don't need that
}
else
echo "Incorrect name or password";

最后,如果您想对登录用户隐藏登录表单,只需将您的登录表单包含在以下 if block 之间:

<?PHP if(isset($_SESSION['username'])): ?>
<script>window.location = 'home.php';</script>
<?PHP else: ?>
<!-- Form element -->
<?PHP endif; ?>

关于PHP 登录表单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31793098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com