Search code examples
phphtmlphp-include

How to change an include file depending on the page


I'm making a website and for all of the pages I've including header.php, which is just a logo and navigation bar at the top of the page, below is the code for the nav menu.

<nav id="navmenu">
<ul>
<li><a href="index.php" class="active">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="portfolio.php">Portfolio</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>
</nav>

How can I make it so that the class="active" changes depending on what page the user is on?


Solution

  • Make use of $_SERVER['PHP_SELF']

    <li><a href="index.php" <?php if ($_SERVER['PHP_SELF'] == "/index.php") echo "class='active'" ?>>Home</a></li>
    
    <li><a href="about.php" <?php if ($_SERVER['PHP_SELF'] == "/about.php") echo "class='active'" ?>>About</a></li>