How to set Navbar item or element as active in PHP

How to set Navbar item as active in PHP ?

To get started, we should have a navbar in our page. It can be bootstrap navbar or a custom one.

We will use the super global variable $_SERVER to fetch the current page name from the url. We will store the page name in a variable and match the variable with all the navbar elements. If the navbar element matches with the value in the variable, then we are going to set that navbar item/element as active.

Code to get the current page name from the url:

<?php $page = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); ?>

The $page variable will have values like "home.php", "about-us.php", etc. irrespective of how many directories inside you are accessing the folder ( Ex: localhost/projects/final/crm/index.php ) . It will give you only the filename ( index.php ).

Below is a simple bootstrap navbar.

<nav class="navbar navbar-expand-lg navbar-light bg-white shadow">
    <div class="container">
      <a class="navbar-brand" href="index.php">
        <img src="assets/images/logo.png" class="web-logo" alt="CRM">

      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">

        <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link <?= $page == 'index.php' ? 'active':''; ?>" href="index.php">Home</a>
          <li class="nav-item">
            <a class="nav-link <?= $page == 'menu.php' ? 'active':''; ?>" href="menu.php">Menu</a>
          <li class="nav-item">
            <a class="nav-link <?= $page == 'about-us.php' ? 'active':''; ?>" href="about-us.php">About Us</a>
          <li class="nav-item">
            <a class="nav-link <?= $page == 'cart.php' ? 'active':''; ?>" href="cart.php">Cart</a>