Jack potato
Jack potato

Reputation: 27

How to resolve Undefined index error in PHP

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.

Upvotes: 0

Views: 1087

Answers (3)

dannjoroge
dannjoroge

Reputation: 608

try below where you are displaying the menu

<nav>
<a id="mainpage">Main Page</a>
<?php if (!isset($_SESSION['logged_in'])) { ?>
    <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 } ?>

Upvotes: 1

Bilal Ahmed
Bilal Ahmed

Reputation: 4066

You should used isset function like

if(isset($_SESSION['logged_in'])){
  // your code
}

Detail: first time session is not set & user is logout and there is no logged_in index in $_SESSION that's why php through warning

also you can use @ for more details

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

Upvotes: 0

Ripon Uddin
Ripon Uddin

Reputation: 714

session_start()
if(isset($_SESSION['logged_in'])){
    echo "SHOW MY LOGGED IN SESSION ".$_SESSION['logged_in'];
}else

Upvotes: 0

Related Questions