0

I want to display the username of the user who logs in while redirecting to the index.php However, when I run the index(Homepage) without logging in. I don't want it to display an error Notice: Undefined index: username.

index.php code:

session_start();
<?= $_SESSION['username'] ?> 

login.php code:

<?php
    session_start();
    $conn = mysqli_connect("localhost", "root", "", "articleZone");

    $message = "";
    if (!empty($_POST["login"])) {
        $result = mysqli_query($conn, "SELECT * FROM users WHERE username='" . $_POST["user_name"] . "' and password = '" . $_POST["password"] . "'");
        $row = mysqli_fetch_array($result);

        if (is_array($row)) {
            $_SESSION["user_id"] = $row['userId'];
            $_SESSION["username"] = $row['username'];
            header("location: index.php");
        } else {
            $message = "Invalid Username or Password!";
        }
    }
    if (!empty($_POST["logout"])) {
        $_SESSION["user_id"] = "";
        session_destroy();

    }
    ?>



    <?php if (empty($_SESSION["user_id"])) { ?>
    form code..
         <?php
                            } else {
                                $result = mysqlI_query($conn, "SELECT * FROM users WHERE userId='" . $_SESSION["user_id"] . "'");
                                $row = mysqli_fetch_array($result);
                                ?>
                                <form action="" method="post" id="frmLogout">
                                    <div>Welcome <?php echo ucwords($row['username']); ?>, You are now logged in.<br>
dalmatian
  • 19
  • 3

2 Answers2

0

You'll want to check against both isset() and empty() before outputting the session:

login.php:

session_start();
if (isset($_SESSION['username'] && !empty($_SESSION['username'])) {
  echo $_SESSION['username'];
}
else {
  // fallback behaviour
}
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

Use isset() to check if the variable exists or not:

if(isset($_SESSION['username'])){
// THEN DO SOMETHING
}

If you only use empty() you will get undefined index

Michael Krikorev
  • 2,126
  • 1
  • 18
  • 25