I just started learning PHP and am having some trouble getting a simple login page to work. When I load this script the first time, the text “Wrong password/username.” and the logout button are printed but not the login form. Why is this happening, and how would I change the code to make the login form and logout button work together as expected?
<?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"); ?>
This part will show “Wrong password/username” when the page loads the first time, because the condition will be false if nothing comes from
$_POST['username'].Add the condition
isset($_POST['username']) && isset($_POST['password'])to both options. Like so:This way nothing of this will be evaluated the first time the page loads, but only when credentials have been posted.