How to Create Dynamic Menu Using PHP and CSS

02nd, January 2018 By

The most of times when we are working in PHP ,special in core PHP we need the menu class will active on the current page.Means our menu will be dynamic and active class will change with page.In core PHP  its very easy to got it.

Dynamic Menu

Way 1

Just copy this code on your main like navigation page at top.Using this code you will get the name of the your current page like /index.php etc.

// current file name 
$CurrentPage = basename($_SERVER["PHP_SELF"]);

Now In your main navigation you have to check if the current page is equal to your menu page.If current page equal to your menu page we will add the activeclass in the menu for active menu.

<div class="menu">
<a href="index.php" <?php if ($CurrentPage == "index.php") echo 'class="active"' ?>>Home</a></li>

<li><a href="about.php" <?php if ($CurrentPage == "about.php") echo 'class="active"' ?>>About</a></li>

<li><a href="contact.php" <?php if ($CurrentPage == "contact.php") echo 'class="active"' ?>>Contact</a></li>



You will add your CSS for active class according to your website design.

Way 2

The second way to make menu dynamic is to check the url will contain the certain string ,its not best but will work making menu dynamic. The stripos() function find out the position of the first occurrence of sub string in a certain string.

<div class="menu">


<li <?php 
if (stripos($_SERVER['REQUEST_URI'],'/about/') !== false) {
echo 'class="active"';
} ?>>
<a href="/about/">About</a></li>



Thus if URL string contain the string ‘about’ than add the active class in the about menu.Hope this will help you.

Leave a Reply

Your email address will not be published. Required fields are marked *