Variable information in included PHP file

I am currently using a PHP file with the footer of my website, so I can just include it on every page and only change one file to change the footer on every page of the site.

Now I would like to do the same with a menu on my site that looks 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>

      

In the active class, the name of the page on which the user is enabled is highlighted, so if the user is on the Menu 2 page of the website, Menu 2 is displayed. Now I'm wondering how I can put this menu in a separate file, for example "menu.php", which I can include on every page, but can still change the class = "active" on the page the user is on.

+3


source to share


3 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>

      

+3


source


Comparison with filename is not best practice and when your project gets heavy it is difficult to maintain

Call footer from page and pass page id -

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

      



in footer.php, maintain the footer inside the 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
}
?>

      

+2


source


Ok, depending on how you move your page, you will have something like mydomain.com\index.php?page=whereyouare

.

Then you can access $_GET['page']

(even in your footer.php) to determine which page you are on and if / else it matches the class correctly = active

I would not recommend using global vars to solve this problem.

0


source







All Articles