So you have moved away from adding the same navigation HTML on each of your static pages and realised you were able to place all the navigation code in one single include file and include that in each of your pages. e.g.
<!--?php include "includes/navigation.php" ?-->
If you haven’t already I would recommend this, because when it comes to altering navigation links, title tags, anchor text, it is a lot quicker to modify the one file, especially if your website is getting bigger and bigger. It makes your working HTML/PHP code a lot tidier and easier to work with.
But you have hit a problem, you wish to highlight to the user which page they are on when they select a link, it used to work when the navigation was static, because you placed an “active” class on the current link in each file, but now your navigation is one file, how can it be done?
It’s simple and can be done in a variety of ways.
Method 1:
First you will need to create a PHP variable that gets the current page: lets create one called “page”… e.g.
$page = $_SERVER['SCRIPT_NAME'];
This can be placed above your navigation code in the same file so it is re-declared each time the page loads.
Then we create our dynamic navigation.
<?php $page = $_SERVER['SCRIPT_NAME']; ?>
<ul class="nav">
<li <?php if ($page == "/index.php"){ echo "class='active'";} ?> ><a href="/">Home</a></li>
<li <?php if ($page == "/about.php"){ echo "class='active'";} ?> ><a href="/">About</a></li>
<li <?php if ($page == "/contact.php"){ echo "class='active'";} ?> ><a href="/">Contact</a></li>
</ul>
In the above you can see that in each listed item the PHP checks if the current page is equal to a certain page, and if so then it echo’s out a class name which will add a visual indication to user that they are on a page.
You will need to add something like this to your CSS.
ul.nav li.active {
font-weight:bold;
text-decoration:underline;
}
Then if someone selects the “about” page, for example it will style your navigation to appear like this:
Home About Contact
Method 2:
An alternative method would be to check if the URL contains a certain string of characters. This works particularity well with directories/folders, for example if you are linking to a WordPress blog from your dynamic navigation, you can do something like below:
<ul>
<li <?php if (stripos($_SERVER['REQUEST_URI'],'/blog/') !== false) {echo 'class="active"';} ?>>
<a href="/blog/">Blog</a></li>
</ul>
The PHP “stripos” function finds the position of the first occurrence of substring in a certain string, in this case the string is the URL which was used in order to access a page, “/blog/… something…”.
So if the substring of “/blog/” within the current URL does not equal false then echo the class “active”, once again an “active” class style will need to be added to your CSS.

One Comment
Excellent, thank you very much (particularly for this method 2). I am a complete noob at php and collecting such wisdom merely by searching the internet.