Michael Falciglia
Michael Falciglia

Reputation: 1046

PHP easier way to hide/show menu items to logged in / logged out users

Is there an easier more efficient way to hide/show menu items to logged in, logged out users? It seems like I should not have to copy the whole menu again with duplicate menu items. The menu items maybe in different order like below

You can see in my example below I have added to links in the <?php } else { ?> statement

<?php
    if($_SESSION["loggedIn"] == "yes") { 
    ?>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="retailers.php">Stores</a></li>
      <li><a href="coupons.php">Coupons</a></li>
      <li><a href="featured.php">Featured Offers</a></li>
      <li><a href="howitworks.php">How It Works</a></li>
      <li><a href="help.php">Help</a></li>
    </ul>

    <?php } else { ?>
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="retailers.php">Stores</a></li>
          <li><a href="coupons.php">Coupons</a></li>
          <li><a href="myaccount.php">My Account</a></li>//logged in item
          <li><a href="featured.php">Featured Offers</a></li>
          <li><a href="howitworks.php">How It Works</a></li>
          <li><a href="help.php">Help</a></li>
          <li><a href="myfavorites.php">My Favorite Stores</a></li>//logged in item
        </ul>
    <?php
    }
?>

Upvotes: 4

Views: 14710

Answers (2)

Jessica
Jessica

Reputation: 7005

Updated for new ordering of items:

<ul class="nav navbar-nav">
  <li class="active"><a href="#">Home</a></li>
  <li><a href="retailers.php">Stores</a></li>
  <li><a href="coupons.php">Coupons</a></li>
  <?php
  if($_SESSION["loggedIn"] == "yes") { 
      echo '<li><a href="myaccount.php">My Account</a></li>';
  }
  ?><li><a href="featured.php">Featured Offers</a></li>
  <li><a href="howitworks.php">How It Works</a></li>
  <li><a href="help.php">Help</a></li>  
  <?php
  if($_SESSION["loggedIn"] == "yes") { 
      echo '<li><a href="myfavorites.php">My Favorite Stores</a></li>';
  }
  ?>  

</ul>

Upvotes: 7

JustinM151
JustinM151

Reputation: 744

Rather than cluttering up the code, you can place the html into multiple PHP files that are loaded in dependant on the logged in user...

switch($_SESSION['userLevel']) {
    case "guest": //Not logged in
        require_once('guestnav.php');
        break;
    case "user": //regular user
        require_once('usernav.php');
        break;
    case "admin": //admin nav
        require_once('adminnav.php');
        break;
    //etc and default nav below
}

then in the nav php files just put the HTML with no PHP and it will be loaded in when the proper criteria is met. makes managing multiple navigation menu's easy.

Upvotes: 4

Related Questions