Highlight currenct open menu item using php - php

I am trying to highlight currently open menu item using PHP.
HTML for my menu items.
<ul class="menu">
<li>Edit Profile</li>
<li>Edit Contact</li>
<li>Edit Facilities</li>
<li>Edit Location</li>
<li>Manage Images</li>
</ul>
This is how I tried it in PHP:
if ($_SERVER['QUERY_STRING']) {
list($queryString) = explode('&',$_SERVER['QUERY_STRING']);
$openPage = $queryString;
list($key, $value) = explode('=',$openPage);
$currentPage = $value;
// Determine what menu item to be highlight:
switch ($currentPage) {
case 'edit-profile':
$class1 = 'class="active"';
break;
case 'edit-contact':
$class2 = 'class="active"';
break;
case 'edit-facilities':
$class3 = 'class="active"';
-----------
// Default is to include the main page.
default:
$class = 'class=""';
break;
} // End of main switch.
} else {
//Determine The Index page
$path = $_SERVER['PHP_SELF'];
$indexPage = basename($path);
$indexPage = basename($path, '.php');
}
This is how I echo these classes in my menus:
<li <?php if(isset($class1)) echo $class1; ?>>Edit Profile</li>
<li <?php if(isset($class2)) echo $class2; ?>>Edit Contact</li>
This is solution is working for me. But my problem is, if I have lot of pages I need to use many class variables in SWITCH case.
Can anybody tell me is there alternative solution for this to minimize my PHP code?
Hope somebody may help me out.
Thank you.

One simple solution would be to store the menu items in a map, and iterate over them:
$menuItems = [
'edit-profile' => [
'url' => 'index.php?p=edit-profile&error=message',
'name' => 'Edit Profile'
],
'edit-contact' => [
'url' => 'index.php?p=edit-contact',
'name' => 'Edit Contacts'
],
...
]
Then iterate over the items.
<ul class="menu">
<?php
foreach($menuItems as $menuItem => $desc) {
// You get $currentPage from the query string
$class = ($currentPage === $menuItem)? 'class="active"': '';
echo '<li '.$class.'>'.$desc['name'].'</li>';
}
?>
</ul>

With this you don't need SWITCH case.
<li <?php if($currentPage=='edit-profile') echo 'class="active"'; ?>>Edit Profile</li>
<li <?php if($currentPage=='edit-contact') echo 'class="active"'; ?>>Edit Contact</li>

You can use array and try like this
if ($_SERVER['QUERY_STRING']) {
list($queryString) = explode('&',$_SERVER['QUERY_STRING']);
$openPage = $queryString;
list($key, $value) = explode('=',$openPage);
$currentPage = $value;
// Determine what menu item to be highlight:
// Store in array, you will be having only one item in array
$class[$currentPage] = 'class="active"';
} else {
//Determine The Index page
$path = $_SERVER['PHP_SELF'];
$indexPage = basename($path);
$indexPage = basename($path, '.php');
}
and the menu can be
<li <?php if(isset($class['edit-profile'])) echo $class['edit-profile']; ?>>Edit Profile</li>
<li <?php if(isset($class['edit-contact'])) echo $class['edit-contact']; ?>>Edit Contact</li>
Note: this not tested, as I have no access to PHP right now.

Rather than doing all this, just take all your menu items in an array and loop over it.
You are sending page parameter with variable.
So, instead have a control over it while sending itself.
Array of page will have page title as key and page url as value.
This way, you do not need separate variables, single variable in loop will serve the job.
<?php
$pages = array(); // Get all page titles and urls in array.
$pages['Edit Profile'] = 'edit-profile&error=message';
$pages['Edit Contact'] = 'edit-contact';
$pages['Edit Facilities'] = 'edit-facilities';
$pages['Edit Location'] = 'edit-location';
$pages['Manage Images'] = 'edit-images';
if (! empty($pages)) {
$current = (isset($_GET['p'])) ? $_GET['p'] : '';
?>
<ul>
<?php
foreach ($pages as $title => $url) {
$active = ($current == $url) ? 'active' : '';
?>
<li><?php echo $title;?></li>
<?php
}
?>
</ul>
<?php
}
?>

Use PHP to generate your own menu structure but for highlighting we can use Jquery.
See example below:
<style>
.active{ background-color:#3F6}
</style>
<ul class="menu">
<li>Home</li>
<li>Edit Profile</li>
<li>Edit Contact</li>
<li>Edit Facilities</li>
<li>Edit Location</li>
<li>Manage Images</li>
</ul>
<script type='text/javascript' src='//code.jquery.com/jquery-1.11.0.js'></script>
<script>
var aurl = window.location.href; // Get the absolute url
$('.menu li a').filter(function() {
return $(this).prop('href') === aurl;
}).parent('li').addClass('active');
</script>

Related

Explode and Set if condition php

Array ( [0] => 1 [1] => 2 )
I'm trying to set an if condition based on user permission, the idea is to show menu based on given values, if it is 1, one menu will be displayed and 2 second menu will be displayed, if its both then all values will be displayed. So far for single values i have gotten it right but how to do it for array of values
This is my code
<?php
$userid = $this->phpsession->get("user_id");
$userrole = $this->phpsession->get("user_type");
$query = $this->db->select("role_empid,role_permissions")->from('hw_role')->where('role_empid', $userid)->get()->result();
$data = $query[0]->role_permissions;
if($data == 1){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }else if($data == 2){ ?>
<li>Request For Proposal</li>
<?php } ?>
</ul>
if role_permission contain json object that first convert it into the array like
$data = $query[0]->role_permissions;
$data=json_decode($data);
otherwise direct check the condition for
$data = $query[0]->role_permissions;
if(in_array(1,$data) && in_array(2,$data))
{
}
else if(in_array(1,$data))
{
}
else if(in_array(2,$data))
{
}
If $query[0]->role_permissions is an array that has distinct value, then you can try :
<ul>
<?php for($i = 0; $i<count($data);$i++) {
if($data[$i] == 1){ ?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if($data[$i] == 2){ ?>
<li>Request For Proposal</li>
<?php }} ?>
</ul>
Try This
<?php
if(in_array(1,$data)){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if(in_array(2,$data)){
?>
<li>Request For Proposal</li>
<?php } ?>

Active current page using php not working

I have this code in header.php:
<?php
$page = "";
?>
<ul class="nav navbar-nav navbar-right nav-pos">
<li <?php if ($page == "home") { ?> class="active"<?php } ?>>Home</li>
<li <?php if($page == 'about') { ?> class="active"<?php } ?>>About us</li>
<li <?php if($page == 'contact'){ ?> class="active"<?php } ?>>Contact us</li>
<li class="hidden-xs"><i class="fa fa-search fa-rotate-90"></i></li>
</ul>
and on every page i put this code(and the name change depends on current page):
<?php include 'header.php';
$page = 'about' ?>
and in css i made this:
.active{color:red }
But it is not working... any idea why?
Thank you for time, I really appreciate it
The problem is that in your header.php you explicitly set $page = "" - which means none of the checks for $page == 'about'(etc) are passing.
Although you do set $page = 'about' in your main script, this is after the code in header.php has run, and its html output produced.
The solution is simple:
1) remove the $page = "" from header.php
2) set $page = "about" (or equivalent) before the include
You can do by using jQuery just adding this script in the footer section.
$(document).ready(function() {
// get current URL path and assign 'active' class
var pathname = window.location.pathname;
$('.nav > li > a[href="'+pathname+'"]').parent().addClass('active');
});
In your case, this will work.
$(function(){
var current = location.pathname;
$('.nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
});
first you should remove $page = ""; from header
<?php
$page = "";//remove this line in header file
?>
<ul class="nav navbar-nav navbar-right nav-pos">
Second in every page swap these two lines
<?php
$page = 'about';//swap these lines
include 'header.php' ;
?>
some details: when header load then $page is empty and your conditions false in li tag. so, before header load you should assign value to $page
the best way: you should used $_SERVER['REQUEST_URI'] instead of hard coded $page. Example:
$url= explode('/',$_SERVER['REQUEST_URI']);
$page = end($request_array);//this show your_page.php
$page=preg_replace('"\.php$"', '', $page )//this will remove .php extension

How can I make a change in the header while I'm using the PHP include?

I'm using include for the header
and it's have this
<li><span>Arrangements</span></li>
<li><span>Build-a-Bouquet</span></li>
<li><span>Special Events</span></li>
and I want only any current opened page get the class="current"
like this
<li class="current"><span>Build-a-Bouquet</span></li>
You can do it like this:
<?php
$menus = array();
$menus['Arrangements'] = 'arrangements.php';
$menus['Build-a-Bouquet'] = 'bouquet.php';
$menus['Special Events'] = 'events.php';
?>
<ul>
<?php
$currnet_page = $_SERVER['PHP_SELF'];
if (! empty($menus)) {
foreach ($menus as $menu => $menu_link) {
$isCurrent = ($currnet_page == $menu_link) ? 'current' : '';
?>
<li class="<?php echo $isCurrent;?>"><span><?php echo $menu;?</span></li>
<?php
}
}
?>
</ul>
Try something like this:
$active = "bouquet";
include("navigation.php");
Navigation:
<li<?php if( isset($active) && $active == "arrangements") echo " class='active'";?>><span>Arrangements</span></li>
... And so on.
This is just a quick example, $_SERVER['PHP_SELF'] can do the job.
<li><span>Arrangements</span></li>
<?php
if($_SERVER['PHP_SELF'] == '/bouquet.php'){
echo '<li class="current"><span>Build-a-Bouquet</span></li>';
}else{
echo '<li><span>Build-a-Bouquet</span></li>';
}
?>
<li><span>Special Events</span></li>
There are a few ways you can do it. Choose the one you like:
1)
Set $current_ var you want and use:
<li><a<? echo isset($current_arrangements) ? 'class="current"' : ''; ?>href="arrangements.php"><span>Arrangements</span></a></li>
<li><a<? echo isset($current_bouquet) ? 'class="current"' : ''; ?>href="bouquet.php"><span>Build-a-Bouquet</span></a></li>
<li><a<? echo isset($current_special_events) ? 'class="current"' : ''; ?>href="events.php"><span>Special Events</span></a></li>
2) same as above but use one variable and check for its value (exactly the way Niet the Dark Absol wrote)
3) wrap it to some function
<?
// Echo Class If Current
function ecic($page) {
echo eregi($page, $_SERVER['PHP_SELF']) ? 'class="current"' : '';
}
?>
<li><a <? ecic('arrangements'); ?>href="arrangements.php"><span>Arrangements</span></a></li>
<li><a <? ecic('bouquet'); ?>href="bouquet.php"><span>Build-a-Bouquet</span></a></li>
<li><a <? ecic('events'); ?>href="events.php"><span>Special Events</span></a></li>
BTW: In most common PHP configurations you can use just <? instead of <?php.

how to apply class according to the filename?

i have created an application where i want to apply active class on active page. Like if fike name starts with me_ then how can i apply class "active" to it.
here is my code:
$pageAttr = basename($_SERVER['REQUEST_URI']);
$files = array("me_dashboard.php","me_my_team.php","me_others.php","me_inbox.php","me_outbox.php");
<li class="<?php echo($pageAttr == $files[0] || $pageAttr == $files[1] || $pageAttr == $files[2] || $pageAttr == $files[3] || $pageAttr == $files[4]) ? "active":"" ?>"><i class="icon-user icon-large"></i> Me</li>
this is not correct code to use. Please suggest me some other ways to achieve the solution in PHP.
If you have array of files like this
$files = array("me_dashboard.php",
"me_my_team.php",
"me_others.php",
"me_inbox.php",
"me_outbox.php"
);
Than you can use in_array() like
<li class="<?php echo (in_array(basename($_SERVER['PHP_SELF']), $files) ? 'active' : '')?>">
It will be even better if you port the class= attribute in the if condition as well, so that you do not get an empty class="" markup.
If you want to refactor your code more, consider porting entire code in a function, and then return the value if condition goes true.
As commented, you wanted to fetch the prefix of the file than you can use substr()
<?php
$page_name = 'me_dashboard.php';
$fetch_prefix = substr($page_name, 0, 3);
echo $fetch_prefix;
?>
<li class="<?php echo (($fetch_prefix == 'me_') ? 'active' : '')?>">A</li>
Demo - Code
you can try this one
<?php
$pageAttr = basename($_SERVER['REQUEST_URI']);
$files = array("me_dashboard.php","me_my_team.php","me_others.php","me_inbox.php","me_outbox.php");
foreach($files as $file)
{
$class_text = "";
if($file==$pageAttr)
{
$class_text = ' class="active" ';
}
?>
<li <?php echo $class_text;?> ><i class="icon-user icon-large"></i> Me</li>
<?php
}
?>

Php $ Html Navigation Issue

Well, Following is the function which select current page name. ex: index.php, owner.php, contactus.php etc. I created this function because i need to active a css id(#active) selector which highlight the current page.
Function
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$pagename = curPageName();
And this is my Navigation Code:
<ul>
<li><a href="index.php" <?php if($pagename == "index.php") echo "id='active'";
?>>HOME</a></li>
<li><a href="owner.php" <?php if($pagename == "owner.php") echo "id='active'"; ?>>LIST
YOUR PROPERTY</a></li>
<?php
$menu = mysql_query("SELECT * FROM page where status = 1");
while($re = mysql_fetch_array($menu))
{
$pageid = $re['pageid'];
$pagelink = $re['pagelink'];
$pagename = strtoupper($re['pagename']);
$pagedes = $re['pagedes'];
echo "<li><a href='page.php?pageid=$pageid'>$pagename</a></li>";
}
?>
<li><a href="contactus.php" <?php if($pagename == "contactus.php") echo "id='active'";
?>>CONTACT US</a></li>
</ul>
So, My questions is It's active the css id selector to Index.php and owner.php. BUT It's doesn't active the css selector to contactus.php page.
Is there anything wrong in my code?
You have overwritten $pagename into while loop
while($re = mysql_fetch_array($menu))
{
$pageid = $re['pageid'];
$pagelink = $re['pagelink'];
$pagename = strtoupper($re['pagename']);
^^^^^ overwritten variable value change this variable name
$pagedes = $re['pagedes'];
echo "<li><a href='page.php?pageid=$pageid'>$pagename</a></li>";
}
-------------------------------------vvvvvvvvv- this will be last value of while loop
<li><a href="contactus.php" <?php if($pagename == "contactus.php") echo "id='active'";
?>>CONTACT US</a></li>

Categories