我刚开始学习 PHP,在让一个简单的登录页面正常工作时遇到了一些麻烦。当我第一次加载这个脚本时,文本“错误的密码/用户名”。并打印注销按钮,但不打印登录表单。为什么会发生这种情况,我将如何更改代码以使登录表单和注销按钮按预期协同工作?
<?php
if (isset($_POST['log_out'])) { // If the page was reloaded as a result of the user having clicked the logout button,
session_destroy(); // kill session.
}
session_start(); // Start a new session with
$_SESSION['user'] = 'foo'; // a static username, and
$_SESSION['pass'] = 'bar'; // a static password.
// If I insert $_SESSION['logged_in'] = 'false'; here to start things off, a blank alert box will be returned no matter from where on the page I alert() the value with JS. On the other hand, without this line the same alert will return "1" both here and further down in the script.
if (($_POST['username'] == $_SESSION['user']) && ($_POST['password'] == $_SESSION['pass'])) { // If the username and password filled in before the page reload match the static ones,
$_SESSION['logged_in'] = true; // the user is logged in.
} else { // If there is no match ...
echo 'Wrong password/username.';
}
include("head.php"); // HTML snippet with everything from the DOCTYPE to the opening BODY tag.
?>
<div> // HTML interlude ...
<?php
// If the user is logged in, print out a logout button in HTML at the top of the page:
if (isset($_SESSION['logged_in']) && ($_SESSION['logged_in'] == true)) {
echo ' <form action="index.php" method="post">';
echo ' <input type="submit" name="log_out" value="Log out">';
echo ' </form>';
}
?>
<p>HTML interlude ...</p>
<?php
// If the user is not logged in, print out a login form in HTML at the bottom of the page:
if ($_SESSION['logged_in'] != true) {
echo ' <form action="index.php" method="post">';
echo ' <label for="username">Username</label><br>';
echo ' <input type="text" name="username" id="username"><br>';
echo ' <label for="password">Password</label><br>';
echo ' <input type="text" name="password" id="password"><br>';
echo ' <input type="submit" name="submit" id="submit" value="Log in">';
echo ' </form>';
}
?>
</div>
<?php include("footer.php"); ?>