Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable info in included PHP file

Currently I'm using a PHP file wih the footer of my website so I can just include it on every page and change just one file to change the footer on every page of the site.

Now, I would like to do the same with the menu on my site which is like this:

<ul>
<li><a href="#">Menu 1</a></li>
<li><a href="#" class="active">Menu 2</a></li>
<li><a href="#">Menu 3</a></li>
<li><a href="#">Menu 4</a></li>
</ul>

The class active highlights the name of the page the user is on, so if the user is at the 'Menu 2' page of the website the li 'Menu 2' is highlighted. Now I wonder how I can put this menu in a seperate file, like 'menu.php' which I can include in every page, but still be able to change the class="active" to the page the user is at.

like image 755
Anoniem Anoniem Avatar asked May 10 '26 05:05

Anoniem Anoniem


2 Answers

$open_page = substr($_SERVER["SCRIPT_NAME"], strrpos($_SERVER["SCRIPT_NAME"],"/")+1);

and

<ul>
<li><a href="#" <?php if($open_page == "Menu_1.php") echo " class= 'active' "; ?>>Menu 1</a></li>
<li><a href="#" <?php if($open_page == "Menu_2.php") echo " class= 'active' "; ?>>Menu 2</a></li>
<li><a href="#" <?php if($open_page == "Menu_3.php") echo " class= 'active' "; ?>>Menu 3</a></li>
<li><a href="#" <?php if($open_page == "Menu_4.php") echo " class= 'active' "; ?>>Menu 4</a></li>
</ul>
like image 186
rvandoni Avatar answered May 11 '26 17:05

rvandoni


Comparing with file-name is not the best-practice & when your project gets heavy, its tough to maintain

Call the footer from page & pass a page identifier-

------ Menu1_page.php --------    
<?php
    require_once 'footer.php';
    getFooter('Menu1');
?>

in footer.php, keep the footer within a function

---- footer.php -----
<?php
function getFooter($activeid){
   ?>
      <ul>
      <li><a href="#" class="<?=($activeid=='Menu1')?'active':''?>">Menu 1</a></li>
      <li><a href="#" class="<?=($activeid=='Menu2')?'active':''?>">Menu 2</a></li>
        ......
      </ul>
   <?php
}
?>
like image 31
Avisek Chakraborty Avatar answered May 11 '26 17:05

Avisek Chakraborty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!