php session logout/login button

A

Anonymous

Guest
want to see if a user is not logged in can not see certain things on the website. If the user is logged the login button changes to logout. Or if a user is not logged in, can not see anything on the page, and if he is logged. I tried to session_start above but the entire page is protected and I do not. I also tried this:
Code:
<? Php if (isset ($ _ SESSION [ 'username'])):?>
<a href="secret/logout.php" class="btn btn-info btn-sm" role="button"> <? php echo $ _SESSION [ 'username']?; ?> </a>
<? Php else:?>
<? Php endif?; ?>

But that does not work. Is there anyone who can help me?
 
Here's how I do it:

Code:
 <?php
if (isset($_SESSION['user']->id) && ( $_SESSION['user']->security === 'member' || $_SESSION['user']->security === 'admin' )) {
  echo '<li><a href="addTrivia.php">Add Trivia</a></li>';
  echo '<li><a href="logout.php">Logout</a></li>';
} else {
  echo '<li><a href="login.php">Login</a></li>';
  echo '<li><a href="register.php">Register</a></li>';
}
?>

When I'm force to intermingle HTML and PHP, I try to do it all in PHP as much as possible. That way it's easier to see what is going on and easier to debug.

HTH John

P.S. I know this hasn't anything to do with this thread, but this is how I had logging out the user.
Code:
    unset($_SESSION['user']);
    session_destroy();
    $_SESSION['user'] = NULL;
    header("Location: index.php");
    exit();
 
Make sure you have session_start() at the beginning of all the pages where you want to use sessions. After a user successfully logs in, you should set a session variable to indicate that the user is logged in. For example:\
$_SESSION['username'] = 'user123'; // Set the session variable to the logged-in user's username
On the pages where you want to display different content based on the user's login status, you can use PHP's if-else conditionals to check if the session variable is set:
<?php if (isset($_SESSION['username'])): ?>
<a href="secret/logout.php" class="btn btn-info btn-sm" role="button"><?php echo $_SESSION['username']; ?></a>
<?php else: ?>
<a href="secret/login.php" class="btn btn-primary btn-sm" role="button">Login</a>
<?php endif; ?>
 
Back
Top