I would like to show or hide a given set of links in the navigation bar of a web application based on the login state of the user.
Below is a snippet of my code;
<nav>
<a id="mainpage">Main Page</a>
<?php if ($_SESSION['logged_in'] === false) { ?>
<a href="login2.php">Login</a>
<a href="register.php">Register</a>
<?php } else { ?>
<a href="post.php">Posting</a>
<a href="#">Members posts</a>
<a href="logout.php" class="outbutton">Logout</a>
<?php } ?>
</nav>
Here, my login page script;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = ($_POST['username']);
$password = ($_POST['password']);
$q = "SELECT * FROM users WHERE username='$username' AND pass='$password'";
$x = $conn->query($q);
if ($x->num_rows > 0) {
while ($row = $x->fetch_assoc()) {
$_SESSION['logged_in'] = true;
header("location: welcome.php");
}
} else {
die("Username or Password is incorrect");
}
My login script works as expected but in the index.php
page, I get the error below when the user is not logged in:
Notice: Undefined index: logged_in
On the other hand, the links get displayed in the navigation bar when a user logs in successfully.
I am using session_start()
at the beginning of my PHP script before any other codes.