Search code examples
phphtmlcss

Active Navigation Bar with PHP?


I'm trying to make an active navigation bar using PHP where the current page will be highlighted or colored in the navigation bar. The code I used:

<ul class="topmenu">
  <li <?php if($_GET['page']="home") { ?> class="active" <?php } ?>>
    <a href="home.php"><b>Bienvenue</b></a>
  </li>
  <li <?php if($_GET['page']="livres") { ?> class="active" <?php } ?>>
    <a href="livres.php"><b>Livres</b></a>
  </li>
  <li <?php if($_GET['page']="bibliotheque") { ?> class="active" <?php } ?>>
    <a href="bibliotheque.php"><b>Bibliothèque</b></a>
  </li>
  <li <?php if($_GET['page']="universite") { ?> class="active" <?php } ?>>
    <a href="universite.php"><b>L'université</b></a>
  </li>
  <li <?php if($_GET['page']="contact") { ?> class="active" <?php } ?>>
    <a href=""><b>Contact</b></a>
  </li>
</ul>

The code will put the attribut in the class active if the page is the current page in the navigation bar. However, all the attributs will be given the class active in this case. How do I fix this?

P.S: I am not looking for any JS or jQuery alternatives, I'm trying to make this work with PHP only.


Solution

  • You could use $_SERVER['SCRIPT_NAME'].

    <ul class="topmenu">
                <li <?php if($_SERVER['SCRIPT_NAME']=="/home.php") { ?>  class="active"   <?php   }  ?>><a href="home.php"><b>Bienvenue</b></a></li>
                <li <?php if($_SERVER['SCRIPT_NAME']=="/livres.php") { ?>  class="active"   <?php   }  ?>><a href="livres.php"><b>Livres</b></a></li>
                <li <?php if($_SERVER['SCRIPT_NAME']=="/bibliotheque.php") { ?>  class="active"   <?php   }  ?>><a href="bibliotheque.php"><b>Bibliothèque</b></a></li>
                <li <?php if($_SERVER['SCRIPT_NAME']=="/universite.php") { ?>  class="active"   <?php   }  ?>><a href="universite.php"><b>L'université</b></a></li>
                <li <?php if($_SERVER['SCRIPT_NAME']=="/contact.php") { ?>  class="active"   <?php   }  ?>><a href="contact.php"><b>Contact</b></a></li>
    </ul>