How To Properly Structure php Navigation Bar - php

I have a index file in my root directory.
I have a directory called pages.
Nav bar is in the includes directory.
If I want to include the navbar in index.php and also in each one of my pages.php which are located in the pages directory. What is the proper way to structure this nav bar so the php can move up and down directories by what page it is on.
each page is identified as
$page = currentPage
And here is my current navbar which is in the includes dir
<ul>
<?php if ($page == 'home') { ?><li class="active">Home</li>
<?php } else { ?><li>Home<?php } ?>
<?php if ($page == 'contact') { ?><li class="active">Contact Us</li>
<?php } else { ?><li>Contact Us<?php } ?>
<?php if ($page == 'services') { ?><li class="active">Services</li>
<?php } else { ?><li>Services<?php } ?>
<?php if ($page == 'employees') { ?><li class="active">Employees</li>
<?php } else { ?><li>Employees<?php } ?>
<?php if ($page == 'dashboard') { ?><li class="active">Dashboard</li>
<?php } else { ?><li>Dashboard<?php } ?>
</ul>
Directory looks like this.
root
root/includes
root/pages
Thanks for your help in advance. I realize I could just do some simple things to get around this but I really want to understand this for the future.
This is how the page is currently laid out:
<?php $page = 'contact'; ?>
<html>
<meta charset="utf-8">
<title>Contact Us</title>
<head>
<base href="http://www.mysite.com/Dir_IM_Working_on_root/pages/" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
</head>
<body>
<div id="wrapper">
<div id="nav">
<?php include '../includes/nav.php'; ?>
</div><!-- CLOSING NAV DIV -->
<div id="main">
</div><!-- CLOSING MAIN DIV -->
<footer>
<?php include '../includes/footer.php'; ?>
</footer>
</div><!-- CLOSING WRAPPER DIV -->
</body>
</html>

Easiest would be to output absolute URLs in all cases. (/test.php)
If you want to leave the possibility to run your site in a subfolder, you can prepend all paths with a variable. This can be changed to the current position of your site.
Another way is to add a
<base href="http://www.example.org/subfolder/" />
to your html code and change that accordingly in combination with absolute URLs. All URLs are based on what you put into the attribute. This is a very elegant solution, but it affects a lot, which might be surprising if one is not that trained in web linkage.
I think there is no "right" way. Typo3 uses the base tag variant and it's most likely the way I would use. Lots of other software use the variable variant (or wrap the path in a function -- which is just another way of achieving the same). Just try some ways and decide for the one which seems most appealing to you I'd say.
In my experience the only thing nearly nobody uses are relative URLs.
Update
Use this html in combination with base html tag.
<ul>
<li<?php if ($page == 'home') echo ' class="active' ?>>Home</li>
<li<?php if ($page == 'contact') echo ' class="active' ?>>Contact Us</li>
<li<?php if ($page == 'services') echo ' class="active' ?>>Services</li>
<li<?php if ($page == 'employees') echo ' class="active' ?>>Employees</li>
<li<?php if ($page == 'dashboard') echo ' class="active' ?>>Dashboard</li>
</ul>

Related

including a css file in html

I have this code for a simple dynamic menu and im trying to include a css file:
<?php
// Get current page file name
$page = basename($_SERVER["PHP_SELF"]);
?>
<html>
<head>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body>
<h1>NTUA Library</h1>
<div id="navigation">
<ul>
<li><a href="index.php" <?php if ($page == "index.php") echo 'class="current"' ?>>Products</a></li>
<li><a href="resume.php" <?php if ($page == "resume.php") echo 'class="current"' ?>>Resume</a></li>
<li><a href="photography.php" <?php if ($page == "photography.php") echo 'class="current"' ?>>Photography</a></li>
<li><a href="about.php" <?php if ($page == "about.php") echo 'class="current"' ?>>About</a></li>
<li><a href="contact.php" <?php if ($page == "contact.php") echo 'class="current"' ?>>Contact</a></li>
</ul>
</div>
</body>
This code is inside a file named menu.php in a directory with this path:C:/xampp/htdocs/php-beginner-crud-level-1/
The css file is in the same directory too.
However changing the css code brings no change to the menu.In window's dev options in network tab for the css file there is Status Code: 304 Not Modified.
What am I missing?

jquery pjax with php. no content at reload

I try to use jquery pjax to load my contents in a div. this works fine, but if i reload the page i have no content. i think i need to put the page content in the else{ part, but i don't want to set the whole html in a php variable. how to fix this?
index.php:
<?php
$title = 'Home';
if(isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX'] == 'true'){ ?>
<div id="content">
<h1>home</h1>
</div>
<?php echo "<title>{$title}</title>";
}else{
include 'wrapper.php';
}
?>
wrapper.php:
<ul class="nav navbar-nav" style='margin-left:20px;'>
<li><a href='index.php' data-pjax='content'>Home</a></li>
<li><a href='page1.php' data-pjax='content'>Demo 1</a></li>
<li><a href='page2.php' data-pjax='content'>Demo 2</a></li>
</ul>
<div id="content"></div>
The JS:
$(document).ready(function() {
$(document).pjax('a[data-pjax]', '#content', {
fragment: '#content'
});
});
page1.php
<?php if(isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX'] == 'true'){ ?>
<div id="content">
<h1>Page 1</h1>
</div>
<?php } else{ include 'wrapper.php';} ?>
page2.php
<?php if(isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX'] == 'true'){
?>
<div id="content">
<h1>Page 2</h1>
</div>
<?php }else{
include 'wrapper.php';
}
?>
You are only including the wrapper.php when the page is requested without PJAX (== the normal way). In wrapper.php the content is empty.
In wrapper.php you should include the correct page if the request origin is not PJAX:
First of all you should rename some files. Use index.php as the main lay-out file (what you intended to do with wrapper). Add the p as query param (which can be read true $_GET in PHP) to load pages when clicking links.
Create a file home.php which will be the default page loaded in #content at index.php.
index.php
<ul class="nav navbar-nav" style='margin-left:20px;'>
<li><a href='index.php' data-pjax='content'>Home</a></li>
<li><a href='index.php?p=1' data-pjax='content'>Demo 1</a></li>
<li><a href='index.php?p=2' data-pjax='content'>Demo 2</a></li>
</ul>
<div id="content">
<?php if(!isset($_SERVER['HTTP_X_AJAX'])) {
if(!isset($_GET['p'])) {
include('home.php');
}
else {
include('page'.$_GET['p'].'.php');
}
} ?>
</div>
This is very simple example. In live applications this should be done in another way to protect the script against certain attacks.
I'm guessing you are a starter. Please take a look at CodeIgniter. It is a framework which has a lot of ready-to-use functions. It has proven to be 'easy' to learn...

Checking if a button was clicked and what was clicked

I'm new to PHP and HTML, I was creating my first website and I found that I would have to repeat a header over and over so I put it in a 'Header.php' file and included it now I have the problem of checking what page they goto. I need to know what page they goto so I can place a 'class="active"' on the page they goto. I may need the code written for me if it isn't too long. Even an example of how you do it showing all the elements will help. Anyhow heres my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Metamorphosis Design Free Css Templates</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<input type="hidden" id="link_is_clicked" name="link_is_clicked" value="0"/>
<link href="styles.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" />
</head>
<body>
<div id="bg_top">
<div id="wrap_bg">
<div id="wrap">
<div id="header">
<div id="menu">
<ul>
<li class="but1_menu">Home</li>
<li class="but2_menu">Blog</li>
<li class="but3_menu">Gallery</li>
<li class="but4_menu">About Us</li>
<li class="but5_menu">Contact Us</li>
</ul>
</div>
<div id="logo">
<h1>metamorph_strongrey</h1>
<small>Small Company Slogan Goes Here</small>
</div>
Thanks for you help.
When it's a small list like you have, I normally would go with a simple if statement:
<li class="but1_menu"><a href="index.php"<?=(($_SERVER['SCRIPT_NAME']=='index.php')?' class="active"':'');?>>Home</a></li>
<li class="but2_menu"><a href="blog.php"<?=(($_SERVER['SCRIPT_NAME']=='blog.php')?' class="active"':'');?>>Blog</a></li>
<li class="but3_menu"><a href="gallery.php"<?=(($_SERVER['SCRIPT_NAME']=='gallery.php')?' class="active"':'');?>>Gallery</a></li>
<li class="but4_menu"><a href="about.php"<?=(($_SERVER['SCRIPT_NAME']=='about.php')?' class="active"':'');?>>About Us</a></li>
<li class="but5_menu"><a href="contact.php"<?=(($_SERVER['SCRIPT_NAME']=='contact.php')?' class="active"':'');?>>Contact Us</a></li>
This will check the current script's name via $_SERVER['SCRIPT_NAME'] and if it matches, it will echo class="active".
First step: Get the current page the user is visiting
$current_url = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
Second step: Create an array containing all menu link pages
$all_urls = array('index.php', 'blog.php', 'gallery.php', 'about.php', 'contact.php');
Third step: Check if the current url is inside the array. If yes, apply the class
<ul>
<li class="but1_menu"><a href="index.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Home</a></li>
<li class="but2_menu"><a href="blog.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Blog</a></li>
<li class="but3_menu"><a href="gallery.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Gallery</a></li>
<li class="but4_menu"><a href="about.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>About Us</a></li>
<li class="but5_menu"><a href="contact.php" <?php if(in_array($current_url, $all_urls)){echo 'class="active"'; } ?>>Contact Us</a></li>
</ul>
All you have to do is place in the href parameter of your anchor tags <a>, a query string indicating what link was pressed.
About Us
Now in your PHP code, you'll want to take a look at the $_GET variable. It is an associative array of all the parameters passed in the URL. So $_GET['action'] will be equal to about.
When you come to write your header once again and want to indicate a "active" link by adding a class, you can just test the action element of the $_GET variable.
Lets assume that in your header file you have an array of links like this -
$headerLinks = array(
'about' => array(
'href'=>'about.php?action=about',
'title'=>'About Us'
),
'home' => array(
'href'=>'home.php?action=home',
'title'=>'Home'
),
'blag' => array(
'href'=>'blag.php?action=blag',
'title'=>'Our Blag'
),
...
);
You would loop over the contents of that array to create your links with the appropriate on having the active class.
foreach($headerLinks AS $key => $link){
$isActive = $_GET['action'] == $key? 'active' : '';
echo ''.$link['title'].'';
}
You should check out this page:
http://php.net/manual/en/reserved.variables.server.php
Specifically the part about REQUEST_URI and that will be what you need. Simply check for this in an if or case statement and apply your class as needed.
You'll only need a few lines of code to check for the uris in your nav bar.
One more method.
Your page will look like
<?php
$curr = "gallery";
include('header.php');
?>
where the $curr variable has a value which could be found in the menu below
and now the menu
<li class="but1_menu"><a <?php echo ($curr == "index" ? "class='active'" : "" ); ?> href="index.php">Home</a></li>
<li class="but2_menu"><a <?php echo ($curr == "blog" ? "class='active'" : "" ); ?> href="blog.php">Blog</a></li>
<li class="but3_menu"><a <?php echo ($curr == "gallery" ? "class='active'" : "" ); ?> href="gallery.php">Gallery</a></li>
<li class="but4_menu"><a <?php echo ($curr == "about_us" ? "class='active'" : "" ); ?> href="about.php">About Us</a></li>
<li class="but5_menu"><a <?php echo ($curr == "contact_us" ? "class='active'" : "" ); ?> href="contact.php">Contact Us</a></li>
To keep code clean is better to use short if/else statement because there is no complex stuff.
Also i recommend to you to put "active" class on <li> but this depends by the style of each developer. In some complex menus it will help you very much.

Changing element ID with javascript

I am loading in the following navbar html from a required PHP file:
<ul id="navlist">
<li id="active">Home</li>
<li>About</li>
<li>News</li>
<li>Applying</li>
<li>Current <br />Residents</li>
<li>Alumni</li>
<li>Contact</li>
</ul>
Depending on the page that I am on (let's say I am on the alumni.php page) I want that list item to be given the ID "active"?
Edit: Here is my header.php code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles/main.css" type="text/css" media="screen" charset="utf-8"/>
<link rel="stylesheet" href="styles/navbar.css" type="text/css" media="screen" charset="utf-8"/>
<title>some title</title>
</head>
<body>
<div id="header">
<div id="left">
<img src="images/tree.png" alt="tree" width="87" height="98"></img>
</div>
<div id="right">
<
</div>
</div>
<div id="navigation">
<ul id="navlist">
<li>Home</li>
<li>About</li>
<li>News</li>
<li>Applying</li>
<li>Current <br />Residents</li>
<li>Alumni</li>
<li>Contact</li>
</ul>
</div>
I assume that I need to do this through Javascript once the page loads? How would I do this?
as said in comment, PHP will be a better way.
You can simple doing it like this :
<?php
$header = file_get_content('header.html');
$page = 'about.php';
$header = str_replace('<li><a href="'.$page.'">', '<li id="active"><a href="#">', $header);
You should assign the ID (which should be a class, semantically speaking, IMHO) using PHP whilst generating the page. Using JS is not only troublesome (you have to go and check your location, probably match a regexp, etc), but also inelegant.
I'd say that in common coding for javascript where you want a particular element to be 'active' or 'highlighted' or 'enabled', make use of the class attribute. Your id attribute implies a static attribute of the data being used.
I think this will do what you want.
<ul id="navlist">
<li id="home">
Home
</li>
<li id="about">
About
</li>
<li id="news">
News
</li>
<li id="applying">
Applying
</li>
<li id="currentResidents">
Current Residents
</li>
<li id="alumni">
Alumni
</li>
<li id="contact">
Contact
</li>
</ul>
<script type="text/javascript">
var pagePath = window.location.pathname;
var pageName = pagePath.substring(pagePath.lastIndexOf('/') + 1);
var currentActive;
function setActivePage(page)
{
if(currentActive)
document.getElementById(currentActive).removeAttribute("class");
document.getElementById(page).setAttribute("class", "active");
currentActive = page;
}
if(pageName == "about.html")
setActivePage("about");
else if(pageName == "otherpage.html")
setActivePage("otherpage");
// Etc...
</script>
If you were using jQuery this may have been done in a better and lesscode way... but I assume you're not using it.
Hope it helps :)
While it may be possible (I haven't actually tried it), you would not typically change the id of an element in the page. Instead, it would be a better approach to use class="active" instead of id="active".
Also, you probably want to generate the appropriate html for it on the server-side, as you're building the rest of the page. Something like this would work (though there are many different ways to build this code, depending on your server's implementation):
<ul id="navlist">
<li class="<?php echo (($currentPage=='Home')?'active':''); ?>">Home</li>
<li class="<?php echo (($currentPage=='About')?'active':''); ?>">About</li>
<li class="<?php echo (($currentPage=='News')?'active':''); ?>">News</li>
<li class="<?php echo (($currentPage=='Applying')?'active':''); ?>">Applying</li>
<li class="<?php echo (($currentPage=='Residents')?'active':''); ?>">Current <br />Residents</li>
<li class="<?php echo (($currentPage=='Alumni')?'active':''); ?>">Alumni</li>
<li class="<?php echo (($currentPage=='Contact')?'active':''); ?>">Contact</li>
</ul>
Note: I've also removed the id="current" attribute from the anchor (<a ...>), because I'm assuming that this would change depending on the current page as well, and it's unnecessary, because you can build CSS selectors to address the anchor, without giving it its own special id or class.
Here's what your CSS might look like:
#navlist li.active {
/* css rules for the active LI */
}
#navlist li.active a {
/* css rules for the active (a.k.a. "current") anchor inside the active LI */
}
hope this helps.
[edit] As I said above, it all depends on the architecture of your php code. But assuming that you have a bunch of php pages (eg: "Home.php", "About.php", "News.php", etc.); and each of those pages includes your nav code using something like: require("nav.php");. Then you can just do the following in each of your main php files:
<?php
/* $currentPage, declared here, will be available to php code inside nav.php */
$currentPage = strtolower(basename(__FILE__));
require("nav.php");
?>
Just be sure that you set $currentPage, in each page's main script, somewhere prior to including your nav code (ie. before you call require(...)). The nav code will then be able to "see" $currentPage and use it.
So, for example, if the above code is executed in a file called "About.php", then $currentPage will be set to "about.php" (filename gets converted to all lowercase by the call to strtolower(...)). Then, when "nav.php" gets included, it will be able to access $currentPage and "see" that we're on the 'about' page.
You can change my example above, as follows, to use values of $currentPage that were generated from the filename using the approach I've described here.
<ul id="navlist">
<li class="<?php echo (($currentPage=='home.php')?'active':''); ?>">Home</li>
<li class="<?php echo (($currentPage=='about.php')?'active':''); ?>">About</li>
<li class="<?php echo (($currentPage=='news.php')?'active':''); ?>">News</li>
<li class="<?php echo (($currentPage=='applying.php')?'active':''); ?>">Applying</li>
<li class="<?php echo (($currentPage=='residents.php')?'active':''); ?>">Current <br />Residents</li>
<li class="<?php echo (($currentPage=='alumni.php')?'active':''); ?>">Alumni</li>
<li class="<?php echo (($currentPage=='contact.php')?'active':''); ?>">Contact</li>
</ul>

How to have current page selection using inludes navigation

I am using php includes to limit redundancy on my pages, how can I have my navigation have the current page selected with say a certain color for the HOME button when my navigation is called from a header.php file.
If i were to say to add a "active" class to the home.php item and add a style so it looked different, that would happen across the board for all my pages, which is why I am using includes in the first place, how can I have one header.php file with my navigation, that also allows each page the ability to show the current page you are on reflected in the navigation?
This is the nav portion of the header.php file
<ul>
<li>About Us</li>
<li>Portfolio</li>
<li>News</li>
<li>Contact</li>
</ul>
This is the index.php file that the header.php file is included in
<?php
include("includes/header.php");
?>
<div class="span-8" id="welcome">
<p>Lorem ipsum</p>
</div>
<div class="span-16 last" id="slideshow">
<img src="images/introImage1.png" alt="fountain">
<img src="images/introImage2.png" alt="bench">
<img src="images/introImage3.png" alt="bridge">
</div>
<?php
include("includes/footer.php");
?>
Try this:
<ul>
<?php
$pages = array('index.php' => 'About Us', 'portfolio.php' => 'Portfolio', 'news.php' => 'News', 'contact.php' => 'Contact');
foreach($pages as $url => $title) {
$li = '<li ';
if($_SERVER[ 'PHP_SELF' ] == $url) {
$li .= 'class="active"';
}
$li .= '>' . $title . '</li>';
echo $li;
}
?>
</ul>
Another option would be to set an attribute against the body tag, and then use a matched pair to change the styling of any number of elements.
So, on your main (home) page, you may have:
<body id="home">
Home
About Us
Then, within your CSS have:
body#home a.home , body#about a.about {
color:#999;background-color:#000; }
And, yet another option would be to include a single CSS statement inside the actual page.
<style type="text/css">
a[href="<?php echo basename( $_SERVER['PHP_SELF'] ); ?>"] ,
a[href="<?php echo $_SERVER['PHP_SELF']; ?>"] {
/* Styles for Current Page Links */ }
</style>
Of course, that is dependent on the browser being able to use that CSS Selector.
And, if you want to be completely sure that all links to the file are covered (including full URIs), then also include the following selector:
a[href="http<?php
echo ( $_SERVER['HTTPS'] ? 's' : '' ).'://'.
$_SERVER['HTTP_HOST'].(
( $_SERVER['HTTPS'] && $_SERVER['SERVER_PORT']!=443 )
|| ( !$_SERVER['HTTPS'] && $_SERVER['SERVER_PORT']!=80 ) ?
':'.$_SERVER['SERVER_PORT'] : '' ).
$_SERVER['PHP_SELF']; ?>"]
UPDATED: Corrected PHP Variables to use.

Categories