- a developer's blog

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