How to set current page "active" in php

Put all the below code in menu.php and everything will be taken care of.

// function to get the current page name
function PageName() {
  return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}

$current_page = PageName();

Use the above to get the current page name then put this in your menu

<li><a class="<?php echo $current_page == 'offnungszeiten.php' ? 'active':NULL ?>" href="offnungszeiten.php">Öffnungszeiten</a></li>
<li><a class="<?php echo $current_page == 'sauna.php' ? 'active':NULL ?>" href="sauna.php">Sauna</a></li>
<li><a class="<?php echo $current_page == 'frauensauna.php' ? 'active':NULL ?>" href="frauensauna.php">Frauensauna</a></li>
<li><a class="<?php echo $current_page == 'custom.php' ? 'active':NULL ?>" href="custom.php">Beauty Lounge</a></li>
<li><a class="<?php echo $current_page == 'feiertage.php' ? 'active':NULL ?>" href="feiertage.php">Feiertage</a></li>

where active is the name of the class which will highlight your menu item


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}

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>

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 } ?>

Tags:

Css

Php