Eric Eric - 7 months ago 61
PHP Question

php after log in successfully, display username at the top of the page?

I was able to make a user register using php and sign in as well. What I am trying to do now is that if I login, it goes to index.html then add "welcome" + username at the top menu bar where the lists below is:

<ul class="nav navbar-nav navbar-right">
<li><a href="mypage.html">My Page</a></li>
<li><a href="register.php">Sign up</a></li>
<li><a href="login.php">Sign in</a></li>
</ul>


I want "welcome"+username before "My Page" only when user login. Please help!

and is there any way I can change "sign in" to "log out" in the same index.html? do I have to create another html file that replaces "sign in" to "log out"?

Thank you!

Answer

In the script that logs the user in, store the user's username and a value that indicates that the user is logged in to $_SESSION like this:

(Place this at the top of the file so that session management can work):

session_start();

Then after valdiating the user add their username and the boolean value to the session superglobal array:

$_SESSION['username'] = <USERNAME>;
$_SESSION['loggedIn'] = true;

To make things work you need to rename your index.html file to index.php so that you can include php tags in it.

After you've done that you can conditionally render both the greeting message and an appropriate button (login / logout) like this:

Start by calling session_start at the beginning of the file:

<?php session_start(); ?>

Then do this to render the greeting message only if the user is logged in:

<?php if($_SESSION['loggedIn']): ?>
<span>Welcome <?php echo $_SESSION['username']; ?></span>
<?php endif; ?>

And this to render a login or logout button:

<?php if($_SESSION['loggedIn']): ?>
<button>Log Out</button>
<?php else: ?>
<button>Log In</button>
<?php endif; ?>
Comments