I am relatively new to PHP, trying to learn more every day.
I have been enjoying using Server Side Includes in my sidebars, footer etc with good results, much handier and more efficient!
I would like to do the same for the header and main site navigation.
However, the main problem that I am not sure how to deal with comes from having ‘active’ links (differently coloured menu tab for the page the user is on) in my menu.
When the user is on the Home page, the class is set to active - i.e. a different colour.
If I do a simple server side include with my navigation this will of course be across all the pages. Can anyone please advise on what I need to do to make the menu work correctly across all the pages? (have different tabs selected for each respective page).
For such a small nav bar then JeremyC’s solution will be fine I’d say, just means hardcoding the file-key “about” in each of your ten files.
<?php
$this_page = "about";
include 'nav_bar.php' ;
?>
If you wanted to do it another way you could detect the filename from your $_SERVER array.
(just do var_dump($_SERVER); on one of your pages to see what else is available to you).
Then you could keep your pages in an array and generate your nav bar from that:
nav_bar.php
<?php
// you just maintain this array, which you keep handy at the top of the file
$pages = array(
'/index.php' => 'Home',
'/about.php' => 'About',
'/contact.php' => 'Contact us',
// etc
);
// grab the var
$this_page = $_SERVER['SCRIPT_NAME'];
#TODO you could test if $this_page exists in the permitted array first
echo '<ul>' ; // start menu
foreach( $pages as $key=>$val ) { // loop thru array
echo '<li><a href="' . $key . '"'; // start nav link
if( $key == $this_page) echo ' class="active"'; // if array key '/index.php' matches $this_page
echo '>' . $val . '</a></li>' . PHP_EOL ; // end nav link
} // end of loop
echo '</ul>' ; // end menu
Sorry, I am unable to test this on my setup today, but that should give you another idea about how you could tackle this problem – but as I say, JeremyCs idea is just fine.
I new in php I use script above in my web but only the last menu appear
<?php
include "configuration/connection.php";
$sql=mysql_query("SELECT * from mainmenu where active='Y' ORDER BY id_main");
while ($m=mysql_fetch_array($sql))
$pages = array(
"$m[link]" => "$m[menu_name]",
// etc
);
// grab the var
$this_page = "$m[link]";
#TODO you could test if $this_page exists in the permitted array first
echo '<ul>' ; // start menu
foreach( $pages as $key=>$val ) // loop thru array
echo '<li><a href="' . $key . '"'; // start nav link
if( $key == $this_page) echo ' class="active"'; // if array key '/index.php' matches $this_page
echo '>' . $val . '</a></li>' . PHP_EOL ; // end nav link
// end of loop
echo '</ul>' ;?>