In PHP how do I display user name at top only after log in?

I am some what new to PHP. I am working on an assignment and am stuck on my final part.

Every page should have a message (preferably at top right of navigation) that shows the current user's username. For example, a message could be something simple like: Welcome James. Once the user logs out, the message should be removed/hidden.

I can get it to show when logged in but when not logged in I get an error.

This is when logged in:

This is when logged in

This is when not logged in:

![This is when not logged in][2]

Notice: Undefined index: username in selectTable.php on line 14

Here is part of login.php

And this is selectTable.php which is just a page that shows a table I made but I need it to just say welcome when not signed in and add register/login too (register.php)


2 answers

  • answered 2020-06-27 05:17 Maarten Veerman

    After logout, you probably cleared the session. This leads to the fact the username is no longer present in the session.

    So your $_SESSION['username'] fails.

    You need to perform a check if the username if still present on the $_SESSION array, before you perform the printout.

    Look into php's array_key_exists function.

    Since you say it's an assignment, I'll not give you the answer by coding it for you, but these tips should help you get our solved.

  • answered 2020-06-27 06:56 Keral Patel

    session_start() is not at the top of the code. It is after the <body> tag.

    Make sure you put it at the very beginning of the script before first byte is outputted.