Dynamically Highlighting the Current Page Menu Label with PHP & CSS

Highlighting the menu label for the current page is a standard norm of web development and is a good practice.  For static websites, it is achieved by defining a css link and hover properties like

selected a,
div#menu ul li.selected a:hover {

The visiting page highlighting is then achieved in html by specifying class=”selected” for the current visited page.

However this manual assignment is neither feasible nor scalable for larger sites. The class=’selected’ assignment needs to done dynamically. And for this we employ a simple piece of php code.

The first thing we require is to obtain the file name of the served php page. We will use $PHP_SELF to do that.
For example, if we use $PHP_SELF in a php file called two.php, $PHP_SELF will return the actual file path.

$path = $_SERVER['PHP_SELF']; // will return for our example
$page = basename($path); // will return two.php
$page = basename($path, '.php'); //will return the string 'two'

Now its easy to check if we are on a given page:

Alternative Method

Alternatively, you may declare an array of variables in your menu.php file like this.


Now on every page in menu links, indicate if you want to assign it the CSS style =’selected’

$present = 1; 
// your rest of the page content goes here

If you have any issues , questions or remarks, do let me know in the comment section.
Thanks for visiting my blog

By Bhaskar

My name is Bhaskar. I am a CTO and a startup techno guy with 10+ years of experience startups.
Full-time coding in Python, React, Java. Part-time coding in C++.
Interested in Music, Travelling

What excites me: anything that has the potential to disrupt the status quo.

Looking for technical support on a startup idea ?
write at : bhaskar {-at-}