How to set current page "active" in php

Hi I have a menu on my site on each page, I want to put it in it's own menu.php file but i'm not sure how to set the class="active" for whatever page i'm on. Here is my code: please help me

menu.php:

<li class=" has-sub">
    <a class="" href="javascript:;"><i class=" icon-time"></i> Zeiten<span class="arrow"></span></a>
    <ul class="sub">
       <li><a class="" href="offnungszeiten.php">Öffnungszeiten</a></li>
       <li><a class="" href="sauna.php">Sauna</a></li>
       <li><a class="" href="frauensauna.php">Frauensauna</a></li>
       <li class=""><a class="" href="custom.php">Beauty Lounge</a></li>
       <li><a class="" href="feiertage.php">Feiertage</a></li>
    </ul>
</li>

Solution 1:

this method gets the current page using php which will pass a word in this case active and places it inside the class parameter to set the page active.

<?php
function active($currect_page){
  $url_array =  explode('/', $_SERVER['REQUEST_URI']) ;
  $url = end($url_array);  
  if($currect_page == $url){
      echo 'active'; //class name in css 
  } 
}
?>
<ul>
    <li><a class="<?php active('page1.php');?>" href="http://localhost/page1.php">page1</a></li>
    <li><a class="<?php active('page2.php');?>" href="http://localhost/page2.php">page2</a></li>
    <li><a class="<?php active('page3.php');?>" href="http://localhost/page3.php">page3</a></li>
    <li><a class="<?php active('page4.php');?>" href="http://localhost/page4.php">page4</a></li>
</ul>

Solution 2:

It would be easier if you would build an array of pages in your script and passed it to the view file along with the currently active page:

//index.php or controller

$pages = array();
$pages["offnungszeiten.php"] = "Öffnungszeiten";
$pages["sauna.php"] = "Sauna";
$pages["frauensauna.php"] = "Frauensauna";
$pages["custom.php"] = "Beauty Lounge";
$pages["feiertage.php"] = "Feiertage";

$activePage = "offnungszeiten.php";


//menu.php
<?php foreach($pages as $url=>$title):?>
  <li>
       <a <?php if($url === $activePage):?>class="active"<?php endif;?> href="<?php echo $url;?>">
         <?php echo $title;?>
      </a>
  </li>

<?php endforeach;?>

With a templating engine like Smarty your menu.php would look even nicer:

//menu.php
{foreach $pages as $url=>$title}
   <li>
       <a {if $url === $activePage}class="active"{/if} href="{$url}">
         {$title}
      </a>
   </li>
{/foreach}

Solution 3:

Create a variable in each of your php file like :

$activePage = "sauna"; (different for each page)

then check that variable in your html page like this

<?php if ($activePage =="sauna") {?>
 class="active" <?php } ?>