php navigation using get or include - php

index.php is controlling the site.
I have elseif include based on variable $p
right now $p does not have anything in it and i'm not understanding why.
Also is using include the industry standard or would GET be a better choice?
In the header file which is included on index.php but it just takes me to the page link instead of storing the page in $p
<?php
$pages = array(
"home" => "HOME",
"services" => "SERVICES",
"employees" => "EMPLOYEES",
"contact" => "CONTACT");
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
echo '<li ';
if ($p == $url) { echo '<li><a class="active" href="' . htmlspecialchars(urlencode($url)). '.php">'
. htmlspecialchars($label) . '</a></li>'; } else { echo '<li>' . $label . '</li>'; }
}
?>
This is the index.php file:
<?php include('includes/header.php'); ?>
<?php
if ($p == "services") {
include("services.php");
} elseif($p == "employees") {
include("employees.php");
} elseif($p == "contact") {
include("contact.php");
} else {
include("home.php");
};
?>
<?php include('includes/footer.php'); ?>

It really depends on what you are trying to do. Maybe I am misunderstanding your question, however include and $_GET are two completely separate things.
$_GET is an array of the query string out of your URL. So, for instance, if your URL was mysite.com/index.php?a=rawr&p=services then $_GET would be array("a" => "rawr", "p" => "services"); If you don't have any parameters in your URL assigned to p, then $_GET["p"] would be empty
Source:
http://www.php.net/manual/en/reserved.variables.get.php
EDIT:
I think I'm starting to understand your question now. Using your current method would be fine, I would just change up the code slightly:
<?php
$pages = array(
"home" => "HOME",
"services" => "SERVICES",
"employees" => "EMPLOYEES",
"contact" => "CONTACT"
);
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
?>
<li><a <?= $p == $url ? 'class="active"' : ""?> href="index.php?p=<?=$url?>" > <?=$label?> </a></li>
<?php
}
?>

Related

How can I remove nested nav from all top-level listed items, except for Services in a PHP array?

I am trying to remove the nested list ($subPages) from displaying under all of the top-level lists ($pages), except for Services; however my code is allowing the nested list items to display under all three top-level list items.
Can anyone help me remove the nested list items from all top-level list items, except for one?
NB. I am new to PHP, and would like to just stick to PHP without any other languages. My PHP code may be in efficient; if you spot room for improvement, let me know.
<nav class="navBar wAuto fRight positAb">
<?php
$pages = array(
'/about/' => 'About',
'/services/' => 'Services',
'/book-a-service/' => 'Book a service'
);
$subPages = array(
'/services/bathroom-installation' => 'Bathroom installation',
'/services/boiler-repair' => 'Boiler repair',
'/services/boiler-service' => 'Boiler service',
'/services/gas-oil' => 'Gas & oil',
'/services/heat-recovery' => 'Heat recovery',
'/services/heating-plumbing' => 'Heating and plumbing',
'/services/rainwater-harvesting' => 'Rainwater harvesting',
'/services/solar-solutions' => 'Solar solutions',
'/services/underfloor-heating' => 'Underfloor heating'
);
$activePage = $_SERVER['REQUEST_URI'];
echo '<ul>';//open nav
foreach( $pages as $url => $anchor){
$activeClass = ($_SERVER['REQUEST_URI'] == $url) ? " active" : "";
echo '<li class="fLeft"><a class="font13'.$activeClass.'" href="'.$url.'"';
if($url == '/services/'){
echo 'id="parent"';
}
if($url == '/book-a-service/')
echo 'id="ctaUHP"';
echo '>'.$anchor.'</a>';
//Open nested nav
if(isset($url) == '/services/'){
echo '<ul class="wAuto positAb">';
foreach ($subPages as $url => $anchor){
echo '<li class="fullWidth"><a class="font10" href="'.$url.'"';//open nested nav
echo '>'.$anchor.'</a></li>';
}
};
echo '</li></ul>'; //close nested nav
}
//Close submenu
echo '</ul>';
//close nav
?>
</nav>
In the code for open nested nav, change if(isset($url) == '/services/') to if($url == '/services/'){
Explanation: You don't need to verify if the $url is set, you just need to print the nested nav when your $url == '/services/', that's why you need to remove the function isset() :)
EDIT
You lacked some {} and I even rearranged some of your code, so now looks like this :)
echo '<ul>'; //open nav
foreach( $pages as $url => $anchor) {
$activeClass = ($_SERVER['REQUEST_URI'] == $url) ? " active" : "";
echo '<li class="fLeft"><a class="font13'.$activeClass.'" href="'.$url.'"';
if($url == '/services/') {
echo 'id="parent"';
}
if($url == '/book-a-service/') {
echo 'id="ctaUHP"';
}
echo '>'.$anchor.'</a>';
//verify if exists nested nav
if($url == '/services/') {
echo '<ul class="wAuto positAb">'; //open nested nav
foreach ($subPages as $url => $anchor) {
echo '<li class="fullWidth"><a class="font10" href="'.$url.'">'.$anchor.'</a></li>';
}
echo '</ul>'; //close nested nav
}
echo '</li>';
}
echo '</ul>'; //close nav

PHP navigation with $_GET method ignoring css active class [duplicate]

This question already has answers here:
how to add active to a tag and li tag with php
(5 answers)
Closed 8 years ago.
My hover links work as well as the navigation, but the active link will not come on.
My CSS active:
#header ul li a.active,
#header ul li a.active:hover {
color:#fff;
background:#000;
font-weight:bold;
Here is my nav.php file:
<ul>
<?php
$pages = array(
"index.php?p=home" => "Home",
"index.php?p=contact" => "Contact Us",
"index.php?p=services" => "Services",
"index.php?p=employees" => "Employees",
"index.php?p=dashboard" => "Dashboard");
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
echo '<li ';
if (preg_match("/$p/",$url)) {
echo "class='active'";
}
echo '><a href=', "$url", '>', "$label", '</a></li>';
}
?>
</ul>
This is my method inside of the index page retrieving each page:
<?php
if (file_exists("pages/$p.php")) {
include("pages/$p.php");
}else{
include("pages/home.php");
}
?>
I suppose that you are using urls like: /index.php?p=page_name
<ul>
<?php
$pages = array(
"home" => "Home",
"contact" => "Contact Us",
"services" => "Services",
"employees" => "Employees",
"dashboard" => "Dashboard");
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
echo '<li ';
if ($p == $url) {
echo "class='active'";
}
echo '>' . $label . '</li>';
}
?>
</ul>

changing colors when link is clicked

If I have a menu set up in the header which I use for most of my pages as "include/header.php" how do I setup so when I click on a link, it goes to that page, and that link changes colors (and shows as active)? Would jquery be good? or PHP?
Thanks!
You could use PHP to add a class to the current button by comparing it's URL, and the current page URL from $_GET. Without knowing what your URL structure is like, I can't say much more than that.
For example, using an array with button text and URLs:
$links = array('Home' => 'home', 'About' => 'about');
foreach($links as $text => $page)
{
if($_GET['page'] == $page)
{
echo '' . $text . '';
}
else
{
echo '<a href="/index.php?page=' . $page . '>' . $text . '</a>';
}
}
This code will add a class of current to the button who's page matches the value in $_GET. This might not exactly fit your needs due to you probably having a different URL structure, among other things, but it gives a basic explanation and example of how to do this.
Use php, you could write a function before your include like so,
function activeLink ($page) {
if ($page = 'home') echo ' class="active"';
elseif ($page = 'about') echo ' class="active"';
elseif ($page = 'posts') echo ' class="active"';
}
And in your header file,
echo '<a href="#"' . activeLink($page) . '>Home</a>
<a href="#"' . activeLink($page) . '>About</a>
<a href="#"' . activeLink($page) . '>Posts</a>';
And on your actual page;
$page = 'home';
include('header');
This will do the trick.

Best way to highlight tabs according to the page you're on with CakePHP?

So prior to being introduced to CakePHP, I'd highlight the appropriate navigation tab according to the url with the following (rather sloppy) code I wrote (fyi absolute_url was a function I wrote to get the absolute path) :
$page = $_SERVER['PHP_SELF'];
// add all possible states for the navigation to an array
$checkNav = array(
"index" => "index",
"new" => "new",
"random" => "random",
"submit" => "submit"
);
$compareAgainst = strpos($page, $checkNav['index']);
if ($compareAgainst == 0) {
echo "<li><span class=\"navBorder\">Popular</span></li>\n";
} else {
echo "<li>Popular</li>\n";
}
$compareAgainst = strpos($page, $checkNav['new']);
if ($compareAgainst == 0) {
echo "<li><span class=\"navBorder\">New</span></li>\n";
} else {
echo "<li>New</li>\n";
}
$compareAgainst = strpos($page, $checkNav['random']);
if ($compareAgainst == 0) {
echo "<li><span class=\"navBorder\">Random</span></li>\n";
} else {
echo "<li>Random</li>\n";
}
$compareAgainst = strpos($page, $checkNav['submit']);
if ($compareAgainst == 0) {
echo "<li><span class=\"navBorder\">+ Submit a Link</span></li>\n";
} else {
echo "<li>+ Submit a Link</li>\n";
}
Now, I've noticed that in Cake, to determine the relative path, I can just go:
<?= $this->here; ?>
Is there a better way to do this, or should I just implement this (new) method with the old code?
You can do the following
Add this to app_helper.php if you need it in multiple pages. You feed this function with the controller and the action you want to check you want to compare against. The function compares it with the current page and return true if they match.
function isActive($controller, $actions = array())
{
foreach ($actions as $action)
{
if ($controller == $this->params['controller'] && $action == $this->params['action'])
{
return true;
}
}
return false;
}
And then generate your links like so:
<ul class="left">
<li <?php if($html->isActive('controller_name', array('index'))) { echo 'class="active"'; } ?>><?php echo $html->link('Index', '/index'); ?></li>
<li <?php if($html->isActive('controller_name', array('new'))) { echo 'class="active"'; } ?>><?php echo $html->link('New', '/new'); ?></li>
<li <?php if($html->isActive('controller_name', array('random'))) { echo 'class="active"'; } ?>><?php echo $html->link('Random', '/random'); ?></li>
<li <?php if($html->isActive('controller_name', array('submit'))) { echo 'class="active"'; } ?>><?php echo $html->link('Submit', '/submit'); ?></li>
</ul>
If the function returns true, the link will have class="active". Adapt it to your needs.
The way I've always done this is to give your body tag an id, and use css to target it. If your views are all separate then you can hard code the body id. If you are using some sort of template that adds in the header, content, footer etc., then just pass the id as a variable to the header view or wherever the body tag is (really any outer container/div that will be on every view and contain your navigation tabs). Also you will need to give your navigation tab id's to target each one.
Then just some css like this:
#homepage a#hometab,
#aboutpage a#abouttab,
#productpage a#productstab,
#contactpage a#contacttab
{
special active styling here
}

How to properly build a navigation menu that highlights the current page

I've setup a menu for a fairly simple site based on icant.co.uk. It's fairly simple with maybe 5 pages. The small site is mainly a mysql browser for a few tables using MATE. Theres a common.php file that contains the header & footer HTML so thats where I put the code below.
The code below highlights the current page on the menu. Its ugly and I'm sure there has to be a better way to do it.
Any help is appreciated, thank you!
heres my code
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
if ($currentFile == "orders.php"){
echo '<li id="active">Orders</li>';
}
else{
echo '<li>Orders</li>';
}
if ($currentFile == "customers.php"){
echo '<li id="active">Customer List</li>';
}
else{
echo '<li>Customer List</li>';
}
if ($currentFile == "order_details.php"){
echo '<li id="active">Order Details</li>';
}
else{
echo '<li>Order Details</li>';
}
?>
UPDATE For those curious, below is the working code!
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "order_details.php", "title" => "Order Details"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$currentAppend = ($page['file'] == $currentFile) ? ' id="current' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '' . $page['title'] .''
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;
?>
What I normally do is something like (for all elements...):
<li class="<?php if (condition) echo 'selected'; ?>">content part, links, etc.</li>
Not sure if that's what you meant, but this way you'll get rid of this ugly if-else:
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '' . $page['title'] .''
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;
A more concise way of doing it (if you have short tags enabled) would be:
<li class="<?= $test=="your_page_name" ? 'selected' : 'not_selected'?>">Link Name</li>
It performs the same function as the first answer, just more concisely.
Here's a snippet from a project of mine. It it old ugly code, and uses tables, but you can just as easily use the idea for divs and cleaner markup. The trick is to make the navigation use a different class if the current page matches it's url.
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_home.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_home.php'>Billing Home</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_schedules.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_schedules.php'>Billing Schedules</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_outstanding.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_outstanding.php'>Outstanding</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_list.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_list.php'>List All</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_history.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_history.php'>Billing History</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_statement_history.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_statement_history.php'>Statement History</a></td></tr>

Categories