Trying to get my PHP navigation bar to work. I am trying to echo the page where the user is on with the attached class of active if the page is current.
Here is my code
Do like this :
$pages = array(
"index.php" => "Home",
"pages/contact.php" => "Contact Us",
"pages/services.php" => "services",
"pages/employees.php" => "Employees",
"pages/dashboard.php" => "Dashboard");
foreach ($pages as $url => $label) {
echo '<li ';
if(basename($_SERVER['REQUEST_URI'])== basename($url)){ // this line
echo "class='active'"; // this line
} // and this line
echo '><a href=', "$url", '>', "$label", '</a></li>';
}
?>
<?php
if ($_SERVER['REQUEST_URI'] === "/page") echo 'id="active"';
?>
<?php
$pages = array(
"index.php" => "Home",
"pages/contact.php" => "Contact Us",
"pages/services.php" => "services",
"pages/employees.php" => "Employees",
"pages/dashboard.php" => "Dashboard");
$cururl = $_SERVER['PHP_SELF'];
foreach ($pages as $url => $label) {
echo '<li';
if (strpos($cururl,$url)!==false) {
echo ' class="active"';
}
echo '><a href=', "$url", '>', "$label", '</a></li>';
}
?>
This should work for you. Because, you were trying to access the url address using GET-METHOD
. Here, I have fetched your url by doing $cururl = $_SERVER['PHP_SELF'];
and checked for the active menu item as if (strpos($cururl,$url)!==false)
Try this:
echo 'class="active"';
Not tested:
<?php
$pages = array(
"index.php" => "Home",
"contact.php" => "Contact Us",
"services.php" => "services",
"employees.php" => "Employees",
"dashboard.php" => "Dashboard");
$uri = explode("/", stripslashes($_SERVER['REQUEST_URI']));
foreach ($pages as $url => $label) {
echo '<li ';
echo in_array($url, $uri)?'class="active"':'';
echo '><a href="'.$url.'">'.$label.'</a></li>';
}
?>
Note: it is a best practice to put your other page files in the root next to yout index.php