Please, I'm new to PHP and I'm building a subscription-based ecommerce site. I've been able to customize the pages such that they look different based on who's browsing what, but I'd like to take the Renew Account off the admin page since they don't have to subscribe.
I've been struggling all day. Please, could someone show me how it could be achieved?
Below is the snippet:
<?php // Show the user info or the login form:
if (isset($_SESSION['user_id'])) {
// Show basic user options:
echo '<div class="title">
<h4>Manage Your Account</h4>
</div>
<ul>
<li>Renew Account</li>
<li>Change Password</li>
<li>Favorites</li>
<li>History</li>
<li>Recommendations</li>
<li>Logout</li>
</ul>
';
// Show admin options, if appropriate:
if (isset($_SESSION['user_admin'])) {
echo '<div class="title">
<h4>Administration</h4>
</div>
<ul>
<li>Add Page</li>
<li>Add PDF</li>
<li>Blah</li>
</ul>
';
}
} else { // Show the login form:
require ('login_form.inc.php');
}
?>
What you could do is to first check if the user admin session is set, to which I added the same conditional value for in the first conditional statement.
If it is set, then assign an empty value for what I named as $renew, with an else{} with the value that I removed from your existing <li></li>.
The first two session arrays here are only representational values of course.
I concatenated the '.$renew.' variable in the menu.
Note: Make sure that the session was started using session_start() inside all pages using sessions; that is not known.
$_SESSION['user_id'] = 123;
$_SESSION['user_admin'] = "john";
if (isset($_SESSION['user_admin'])) {
$renew = '';
} else {
$renew = '<li>Renew Account</li>';
}
if (isset($_SESSION['user_id'])) {
// Show basic user options:
echo '<div class="title">
<h4>Manage Your Account</h4>
</div>
<ul>
'.$renew.'
<li>Change Password</li>
<li>Favorites</li>
<li>History</li>
<li>Recommendations</li>
<li>Logout</li>
</ul>
';
// Show admin options, if appropriate:
if (isset($_SESSION['user_admin'])) {
echo '<div class="title">
<h4>Administration</h4>
</div>
<ul>
<li>Add Page</li>
<li>Add PDF</li>
<li>Blah</li>
</ul>
';
}
}
Try..
If(!isset($_SESSION['user_admin'])) {echo '<li>Renew Account</li>'; }
This way if it the session variable for admin is set the echo won't occur.
In my application there is a page where I generate dynamic links based on the data from mysql DB. My task is to set a class="active" for the selected link. If the links where static I can give active class using page name like this. But what to do in my case? Is there any way to get this done?
Here is my code:
<div class="select-region clearfix">
<input type="hidden" id="rgnId" name="rgnId">
<input type="hidden" id="hltypId" name="hltypId">
<ul class="nav">
<li>Select your region</li>
<li value="0"><a class="active" id="show_0" onClick="UAEHolydayDetails(0)">All<span class="badge"><?php echo $uaedetailscount?></span></a></li>
<?php
$i=0;
while($rowrgn = $rsltrgn->fetchAssoc())
{
?>
<li><a id="show_<?php echo $rowrgn['rgnId']; ?>" onClick="UAEHolydayDetails(<?php echo $rowrgn['rgnId']; ?>)"><?php echo $rowrgn['rgnName']; ?><span class="badge">
<?php echo $rowrgn['regioncount'];?></span></a></li>
<?php } ?>
</ul>
</div>
can anyone please help me
Edit 1
when I click any of these dynamic links it passes an id to the same page through js and the page will be filled with data from DB based on this paseed id like this:
onClick="UAEHolydayDetails(<?php echo $rowrgn['rgnId']; ?>)"
js:
<script>
function HolytypeDetails(id){
$('#hltypId').val(id);
window.location='uae-holidays.php?hltypId='+id;
}
</script>
in script the page in window.location is the page where the links are generated itself
Of course. It's the same thing. You need to know your active item id and based on this information just chose the item you want.
<?php
$activePageId = 5;
$i=0;
while($rowrgn = $rsltrgn->fetchAssoc())
{
?>
<li <?php if($rowrgn['rgnId'] === $activePageId){ ?>class="active"<?php } ?>><a id="show_<?php echo $rowrgn['rgnId']; ?>" onClick="UAEHolydayDetails(<?php echo $rowrgn['rgnId']; ?>)"><?php echo $rowrgn['rgnName']; ?><span class="badge">
<?php echo $rowrgn['regioncount'];?></span></a></li>
<?php } ?>
You may just use a selector to grab it via the href
Example with jquery:
$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
I have a site that uses query strings to retrieve the data like so:
<div id="menu-sort-dropdown" class="search-filter-item">
<p><?php echo $query_sort_title; ?></p>
<ul class="dropdown-menu">
<li>Newest</li>
<li>Oldest</li>
<li>Alphabetically</li>
</ul>
</div>
<div id="menu-category-dropdown" class="search-filter-item">
<p><?php echo $query_category_title; ?></p>
<ul class="dropdown-menu">
<li>All</li>
<li>Coaching</li>
<li>Conversation</li>
<li>Craft</li>
<li>Creativity</li>
</ul>
</div>
It works great getting the data like:
teachings/?sort=SORT_NAME_ASC
or
teachings/?category=Creativity
but I can do both like:
teachings/?category=Creativity&sort=SORT_NAME_ASC
I can't wrap my head around how to add that. If I just append the strip it will become a mess.
The following code doesn't 'duplicate' the values in the url if you keep clicking the category or sort. It's made to copy/paste and run.
// to check the values
echo '<pre>';
print_r($_GET);
echo '</pre>';
echo '<hr>';
function foo($type, $value){
$args = $_GET;
$args[$type] = $value; // prevent duplication
return http_build_query($args); // returns new query string
}
?>
SORT_DATE_LIT_ASC
<br>
SORT_NAME_ASC
<br>
Coaching
<br>
Conversation
You can also have a code to remove any of those. Add it right after the previous code (also copy/paste). Take a look:
<?php
function bar($type){
$args = $_GET;
unset($args[$type]);
return http_build_query($args); // returns new query string
}
?>
<hr>
Remove SORT
<br>
Remove CATEGORY
As for now your dropdown element do a simple action - go to provided url. If you want to select a few values then your elements should store selected value instead of open url. You can do this with for example this JS code
var menus = [];
function addElement(type, element) {
menus[type] = element;
}
The type above is number index of your menu type. For example 0 can be for sort and 1 for category - this is for ensure that you can select only one value from menu type. Now you can replace your code with something like this
<div id="menu-sort-dropdown" class="search-filter-item">
<p><?php echo $query_sort_title; ?></p>
<ul class="dropdown-menu">
<li>Newest</li>
<li>Oldest</li>
<li>Alphabetically</li>
</ul>
</div>
<div id="menu-category-dropdown" class="search-filter-item">
<p><?php echo $query_category_title; ?></p>
<ul class="dropdown-menu">
<li>All</li>
<li>Coaching</li>
<li>Conversation</li>
<li>Craft</li>
<li>Creativity</li>
</ul>
</div>
To go to the prepared URL you need to add another element like for example a button (or something else with calling openUrl function after mouse click)
<input type="button" onclick="openUrl('?')" value="Go to URL">
And the JS code for openUrl function
function openUrl(prefix) {
var url = prefix + menus.join('&');
document.location.href = url;
}
This question already has answers here:
Hiding a Div using php
(6 answers)
Closed 1 year ago.
I have a foreach look that checks if user has a picture or not. If the user doesn't have the picture I want to hide a <li> tab that shows the picture.
Inside my else how do I say, for this user hide tab 2?
I tried using echo 'id="tabHeader_2" style:"visibility:hidden"; but that doesn't work. I need a reference to that tab2, don't I?
<div id="picture<?php echo $i ?>" style="display: none;">
<?php
$picture = $user->pic;
if(isset($picture))
{
// show picture.
}
else
{
// hide tab2
}
?>
</div>
Then the list of tabs:
<div class="profiles">
<div id="tabContainer">
<div class="tabs">
<ul>
<li id="tabHeader_1"> Profile </li>
<li id="tabHeader_2"> Picture </li>
</ul>
</div>
<div id="tabsContent">
<div class="tabpage" id="tabpage_1"></div>
<div class="tabpage" id="tabpage_2"></div>
</div>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/tabs.js"></script>
</div>
</div>
Picture of what the page looks like:
I am not 100% sure about your code, but you are using isset() which would not be correct, because you set the variable right behind that check so it will be set 100% of the time. You will want to check empty() or is_file() perhaps, depends on what is in that variable.
<!-- This display: none seems strange if you are going to show the wrapped elements -->
<div id="picture<?php echo $i ?>" style="display: none;">
<?php
$picture = $user->pic;
if(!empty($picture)) {
// show picture.
}
else {
// hide tab2
}
?>
</div>
If you put the real code, it would be easier to see how you are laying out your elements.
Do Like This :-
<div class="tabs">
<ul>
<?php
$i = 1;
foreach($yourarray as $key => $value){
if(isset($value) && $value != '')
?>
<li id="tabProfileHeader<?php echo $i;?>"> Profile </li>
<li id="tabPictureHeader<?php echo $i;?>"> Picture </li>
<?php
$i++;
}
?>
</ul>
</div>
Hi I have a menu on my site on each page, I want to put it in it's own menu.php file but i'm not sure how to set the class="active" for whatever page i'm on.
Here is my code: please help me
menu.php:
<li class=" has-sub">
<a class="" href="javascript:;"><i class=" icon-time"></i> Zeiten<span class="arrow"></span></a>
<ul class="sub">
<li><a class="" href="offnungszeiten.php">Öffnungszeiten</a></li>
<li><a class="" href="sauna.php">Sauna</a></li>
<li><a class="" href="frauensauna.php">Frauensauna</a></li>
<li class=""><a class="" href="custom.php">Beauty Lounge</a></li>
<li><a class="" href="feiertage.php">Feiertage</a></li>
</ul>
</li>
this method gets the current page using php which will pass a word in this case active and places it inside the class parameter to set the page active.
<?php
function active($currect_page){
$url_array = explode('/', $_SERVER['REQUEST_URI']) ;
$url = end($url_array);
if($currect_page == $url){
echo 'active'; //class name in css
}
}
?>
<ul>
<li><a class="<?php active('page1.php');?>" href="http://localhost/page1.php">page1</a></li>
<li><a class="<?php active('page2.php');?>" href="http://localhost/page2.php">page2</a></li>
<li><a class="<?php active('page3.php');?>" href="http://localhost/page3.php">page3</a></li>
<li><a class="<?php active('page4.php');?>" href="http://localhost/page4.php">page4</a></li>
</ul>
It would be easier if you would build an array of pages in your script and passed it to the view file along with the currently active page:
//index.php or controller
$pages = array();
$pages["offnungszeiten.php"] = "Öffnungszeiten";
$pages["sauna.php"] = "Sauna";
$pages["frauensauna.php"] = "Frauensauna";
$pages["custom.php"] = "Beauty Lounge";
$pages["feiertage.php"] = "Feiertage";
$activePage = "offnungszeiten.php";
//menu.php
<?php foreach($pages as $url=>$title):?>
<li>
<a <?php if($url === $activePage):?>class="active"<?php endif;?> href="<?php echo $url;?>">
<?php echo $title;?>
</a>
</li>
<?php endforeach;?>
With a templating engine like Smarty your menu.php would look even nicer:
//menu.php
{foreach $pages as $url=>$title}
<li>
<a {if $url === $activePage}class="active"{/if} href="{$url}">
{$title}
</a>
</li>
{/foreach}
Create a variable in each of your php file like :
$activePage = "sauna"; (different for each page)
then check that variable in your html page like this
<?php if ($activePage =="sauna") {?>
class="active" <?php } ?>
Put all the below code in menu.php and everything will be taken care of.
// function to get the current page name
function PageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$current_page = PageName();
Use the above to get the current page name then put this in your menu
<li><a class="<?php echo $current_page == 'offnungszeiten.php' ? 'active':NULL ?>" href="offnungszeiten.php">Öffnungszeiten</a></li>
<li><a class="<?php echo $current_page == 'sauna.php' ? 'active':NULL ?>" href="sauna.php">Sauna</a></li>
<li><a class="<?php echo $current_page == 'frauensauna.php' ? 'active':NULL ?>" href="frauensauna.php">Frauensauna</a></li>
<li><a class="<?php echo $current_page == 'custom.php' ? 'active':NULL ?>" href="custom.php">Beauty Lounge</a></li>
<li><a class="<?php echo $current_page == 'feiertage.php' ? 'active':NULL ?>" href="feiertage.php">Feiertage</a></li>
where active is the name of the class which will highlight your menu item
there is two things you can do.
first you can read the current filename of the php file you request by using $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'] or any other $_SERVER global variables that you can use to read your current page and compare it with the link's url, something like this
<a href="offnungszeiten.php" <?php if($_SERVER['PHP_SELF']=='offnungszeiten.php'){ ?>class="activatepage" <?php } ?> >
Öffnungszeiten
</a>
the second one is to create a variable that you can read globally that would store the current name of the current page, like this
<?php
$cur_page ="offnungszeiten"
?>
<a href="offnungszeiten.php" <?php if($cur_page=='offnungszeiten'){ ?>class="activatepage" <?php } ?> >
Öffnungszeiten
</a>
I have done it with php in this way,
function createTopNav($active)
{
$pages = array(
array(
'name'=>'Home',
'link'=>'index'
),
array(
'name'=>'Smartphone',
'link'=>'smartphone'
),
array(
'name'=>'Tablet',
'link'=>'tablet'
),
array(
'name'=>'About Us',
'link'=>'about'
),
array(
'name'=>'Contact Us',
'link'=>'contact'
)
);
$res = "<ul>";
$activePage = "";
foreach($pages as $key=>$val)
{
if($val['link']==$active)
{
$res.= "<li><a href='".$val['link']."' class='active' >".$val['name']."</a></li>";
}
else
{
$res.= "<li><a href='".$val['link']."'>".$val['name']."</a></li>";
}
}
$res.="</ul>";
return $res;
}
And then to call this function
echo createTopNav("about");
and the output will be like this
<ul>
<li>Home</li>
<li>Smartphone</li>
<li>Tablet</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
I solved this using jQuery/javascript by running the code below each time my any page is loaded:
$(document).ready(function () {
//Get CurrentUrl variable by combining origin with pathname, this ensures that any url appendings (e.g. ?RecordId=100) are removed from the URL
var CurrentUrl = window.location.origin+window.location.pathname;
//Check which menu item is 'active' and adjust apply 'active' class so the item gets highlighted in the menu
//Loop over each <a> element of the NavMenu container
$('#NavMenu a').each(function(Key,Value)
{
//Check if the current url
if(Value['href'] === CurrentUrl)
{
//We have a match, add the 'active' class to the parent item (li element).
$(Value).parent().addClass('active');
}
});
});
This implementation assumes your menu has the 'NavMenu' ID, and uses http://hostname/scriptname.php href attributes like so:
<ul id="NavMenu">
<li>Home</li>
<li>Smartphone</li>
<li>Tablet</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
Read the javascript comments to see what's going on. If you prefer to use a different href layout (like in your original example), you have to play with the CurrentUrl variable a bit to get it to use the same layout as your href attributes.
For me this was the easiest solution since I had an existing sites with a big menu and many pages, and wanted to avoid having to modify all pages. This allows me to throw in a piece javascript code in the header file (which was a central file already) which solves the problem for all existing pages.
A bit late on the ball, but I just had to solve this myself and ended up using this Javascript method, with a small modification. This has the advantage on not requiring many changes to the current code, just run the script and voila.
window.onload = activateCurrentLink;
function activateCurrentLink(){
var a = document.getElementsByTagName("A");
for(var i=0;i<a.length;i++)
if(a[i].href == window.location.href.split("#")[0])
a[i].className = 'activelink';
}
Send page name in query string and check it on every page by getting the variable.
Simplere solution:
Borrowing the code from asprin above;
Create a new file menu.php where you will store the one and only copy of the menu. In this file, you will create a function addMenu($pageName) that take a parameter as the page name and returns a string consisting of the menu after having added the current tag.
In your HTML code, you would include(menu.php) and then call the function addMenu with the current page name. So your code will look like this:
menu.php
<?php
function addMenu($pageName){
$menu =
'<ul>
<li><a href="Öffnungszeiten.php"' . ($pageName == "Öffnungszeiten" ? "class=\"current\"" : "") . '><span>Öffnungszeiten</span></a></li>
<li><a href="sauna.php"' . ($pageName == "Öffnungszeiten" ? "class=\"current\"" : "") . '><span>Sauna</span></a></li>
<li><a href="frauensauna.php"' . ($pageName == "Frauensauna" ? "class=\"current\"" : "") . '><span>Frauensauna</span></a></li>
<li><a href="custom.php" ' . ($pageName == "lounge" ? "class=\"current\"" : "") . '><span>Beauty Lounge</span></a></li>
<li><a href="Feiertage.php"' . ($pageName == "feiertage" ? "class=\"current\"" : "") . '><span>Feiertage</span></a></li>
</ul>';
return $menu;
}
?>
And in your HTML, say this:
<div id="menu">
<?php
include('menu.php');
echo addMenu("index");
echo $hello;
?>
</div>
This worked for me:
function active_page($script){
$actual = basename($_SERVER['PHP_SELF']);
if($script == $actual){
return 'active-page'; //class name in css
}
}
I have some simple example, see below:
<?php
function active($currect_page) {
$url = $_SERVER['REQUEST_URI'];
if($currect_page == $url){
echo 'active';
}
}
?>
<ul class="navbar-nav mr-auto">
<li class="nav-item <?php active('/');?>">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item <?php active('/other');?>">
<a class="nav-link" href="/other">Other page</a>
</li>
</ul>
Better late than never - I like to keep it simple, to be honest, especially if there's a ton of scripting and PHP going on.
I place this code on the top of each page to identify the page:
<?php
$current_page = 'home';
include 'header.php';
?>
Then your menu/navigation (mine is bootstrap 4) looks like this:
<ul class="navbar-nav mx-auto">
<li class="nav-item <?php if ($current_page=="home") {echo "active"; }?>">
<a class="nav-link" href="<?php echo SITEURL;?>/">Home</a>
</li>
<li class="nav-item <?php if ($current_page=="about") {echo "active"; }?>">
About
</li>
<li class="nav-item <?php if ($current_page=="store") {echo "active"; }?>">
Store
</li>
<li class="nav-item <?php if ($current_page=="news") {echo "active"; }?>">
News
</li>
<li class="nav-item <?php if ($current_page=="contact") {echo "active"; }?>">
Contact
</li>
</ul>
I'm not saying this is the optimal method, but it works for me and it's simple to implement.
adding this:<?= ($activePage == 'home') ? 'active':''; ?> to my link it works perfectly, I only can't make the child of a submenu working to make the parent active.
Assume you have a navbar with the following items:
<ul>
<li id="menu-item-home">HOME</li>
<li id="menu-item-services">SERVICES</li>
<li id="menu-item-about-us">ABOUT US</li>
<li id="menu-item-contact">CONTACT</li>
</ul>
Then, declare a javascript variable in each page as below:
<script>
<?php echo("var active = 'menu-item-home';"); ?>
</script>
The variable "active" is assigned with the corresponding item of each page.
Now, you can use this variable to highlight the active menu item as below.
$(window).ready(function(){$("#" + active).addClass("active");});
I have a similar issue with my web app menu.
I also have sub menus which do not appear as top level menu buttons.
My solution is as follows:
a) Partial php file with menu html and a little php function at the top that checks GET variables against the menu buttons.
I have two GET variables to check: the page and (if necessary) the menu_button.
b) Adding any new php page with a href links to either menu pages or sub menu pages.
The variable "menu_button" is optional and can be used to link to submenu php files.
Of course the security concerning GET variables should be considered.
From my point of view, this solution has less effort than having to maintain an array of pages or links somewhere.
You just use a get variable "menu_button" where you pass the top level menu button that should be marked visually in any link which targets your php file.
Code examples:
Partial menu.php (has to be included in every php file):
<?php
function active($page_link){
$menu_button = $_GET("menu_button") ?: $_GET("page"); // sets the menu button either to the given top level menu or it defaults to the page itself
if($menu_button === $page_link) return "active";
}
?>
<div>
<a href="?page=one" class="<?= active('one') ?>"Link one</a>
Link two
</div>
Any php file with links to sub menu file:
<div>
Link one
Link to sub menu page "three" of menu "two"
</div>
Works for me. Hope someone else can use this.
For making a dynamic active menu link I follow this method.
first, In the menu link, I always use the full address:
//HTML CODE
<ul class="menu">
<li>
Home
</li>
<li>
About us
</li>
<li>
Contact
</li>
</ul>
//Javacript Code
const menus = document.querySelectorAll('.menu li a');
menus.forEach((menu) => {
const currentLocation = window.location.href;
if (currentLocation === window.origin) {
menus[0].classList.add('active');
} else if (menu.href === currentLocation) {
menu.classList.add('active');
} else {
return;
}
});
and then I will use vanilla javascript code to do the rest
You can use
<?php
function active($current_page){
$page = $_GET['p'];
if(isset($page) && $page == $current_page){
echo 'active'; //this is class name in css
}
}
?>
<ul>
<li><a class="<?php active('page1');?>" href="?p=page1">page1</a></li>
<li><a class="<?php active('page2');?>" href="?p=page2">page2</a></li>
<li><a class="<?php active('page3');?>" href="?p=page3">page3</a></li>
<li><a class="<?php active('page4');?>" href="?p=page4">page4</a></li>
</ul>