Dynamic navigation using PHP include - php

I have a question about how I can dynamically change the content to display in the webpages.
I have few portions of the website fixed - header, nav, footer, and splash and a side bar.
I only want the middle portion of my website to change based on the menu link what user clicks on.
Below is my code for index.php
<?php
include "/templates/header.php";
include "templates/menu.php";
include "/templates/splash.php";
$action = "index";
$disallowed_paths = array('header','menu','splash','bottom_page', 'footer');
if (!empty($_GET['action']))
{
$tmp_action = basename($_GET['action']);
if (!in_array($tmp_action, $disallowed_paths) && file_exists("/content/$tmp_action.php"))
$action = $tmp_action;
}
include "/content/$action.php";
include "/templates/bottom_page.php";
include "/templates/footer.php";
?>
My menu.php contains links for Home, About, products, services and login links
I just want to change the main_index.php to include the above based on what user clicks on.
please advise if this approach is good.
or should I create similar file as index.php multiple times with includes to each file as per the link clicked on menu

Your Answer is
GET method
You can use get method for that
<ul>
<li>example 1</li>
<li>example 2</li>
<li>example 3</li>
<li>example 4</li>
</ul>
After User Clicks on the link
<?php
if(isset($_GET['page']) && $_GET['page']!=""){
$page = "";
switch ($_GET['page']) {
case 'example_1':
$page = "Page_1.php";
break;
case 'example_2':
$page = "Page_2.php";
break;
case 'example_3':
$page = "Page_3.php";
break;
case 'example_4':
$page = "Page_4.php";
break;
default:
$page = "any_default_page.php";
break;
}
include($page);
}
?>
And there are other ways also. but this is the most easy and efficient

I think better approach would be whitelisting instead of blacklisting.
$existing_pages = array('home', 'contact', 'terms-of-service');
if(isset($_GET['action'] && in_array($_GET['action'], $existing_pages)
{
// load action here
} else {
//show 404 error
}
Note that your overall approach is not ideal, you could look like into modern frameworks like Laravel or Symphony which has templating systems which helps alot.
But for learning purposes this is fine:)

Related

Dynamic CSS classes

My website has a simple navigation using a styled <ul> list, with the current page's link highlighted. Currently, I do this by giving the <a> object a CSS class like this:
<ul class="bd-nav">
<li>Home</li>
<li>Contact</li>
</ul>
with the corresponding CSS:
.bd-nav-active {
background-color: #563a64;
}
This works perfectly. However, I would like to build the website with PHP and have a seperate file for the header/navigation and then just <?php include ?> that file on every other page.
Is there a way to dynamically set the class of the navigation links, depending on which page you're on? What would be the best approach here?
Solved after some fiddling! I simply put the class attribute into a variable like this: (make sure to escape the quotation marks!)
<?php
$nav_active = "class=\"bd-nav-active\""
?>
Then used that variable in my navigation like this:
<ul class="bd-nav">
<li><a href="index.html" <?php if ($pid == 1) echo $nav_active; ?>>Home</a></li>
<li><a href="contact.html" <?php if ($pid == 2) echo $nav_active; ?>>Contact</a></li>
</ul>
And then on the respective pages, I simply set the $pid variable:
<?php $pid = 1; ?>
Works perfectly! Thanks for the helpful answers!
#Arrabidas92 had a nice way to automatically do this by getting the page URL, but I think I'll be doing it like this to have better control over how the navigation looks.
The menu needs to be dynamically generated and each page needs to have a unique id or something at the top of the page.
When you dynamically generate the menu, insert and if clause that will echo the active class if generated menu item is the same with current page.
I have not coded in php for some time now but i use to do something like this, in each page give a unique file name at the top. For example in the home page:
<?php
$file_name = "index.php";
?>
and then in the included file apply a logic like this:
<?php
if($file_name == "index.php"){
//Your navigation for the home page
}
else if($file_name == "about.php"){
//Your navigation for the about page
}
?>
Alright so I will give you some tips. First, to know on wihch page of your website you are you can use in PHP a superglobal called $SERVER with this attribute : $_SERVER['REQUEST_URI'].
By calling this, PHP is going to return the parts of the url after your domain.com. For example, if the current url was domain.com/home, echo will return only '/home'.
Then, you can place your logic about highlighting your links :
if($_SERVER['REQUEST_URI' == '/home') {
//Add active class to the link HOME
}...
You can try this one, but this is a Jquery, just put the CDN in your file.
$(document).ready(function(){
if(window.location.href === "index.php") {
$(".bd-nav").addClass("active-bgRed");
}
else if(window.location.href === "about.php") {
$(".bd-nav").addClass("active-bgBlue");
}
else if(window.location.href === "contact.php") {
$(".bd-nav").addClass("active-bgGreen");
}
});
// CSS
.active-bgRed{
background-color: red;
}
.active-bgBlue{
background-color: blue;
}
.active-bgGreen{
background-color: green;
}
// JQuery CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Apply CSS class to clicked link from multiple links to same page, different sections

I have 3 links that all point to the same page but to different sections.
This is what the page sections look like, they are all similar- just read from different tables.
<h1>Networking</h1>
<?php
include 'inc/connect.php';
$data = mysqli_query($link, "SELECT * FROM networking WHERE id = 1")or
die(mysqli_error($link));
while($info = mysqli_fetch_array( $data )) {
echo nl2br($info['info']);}
?>
</article>
This is the part of the menu file that has a link to 'Networking'.
if ($page == 'system') {
$output .="<li><a href='system.php#networking' class='active'>Networking</a></li>";}
else{
$output .="<li><a href='system.php#networking'>Networking</a> </li>";}
All the page section are in a page called system.php.
In the head of system.php I have this line
<?php $page = 'system'; ?>
This so I can apply the css class 'active' to the active link.
The way it is now, when I click on any 1 of my same page different section link the the class 'active' is applied to all 3 menu items.
Is there a way that I can apply the class to only the clicked link?
I understand your problem, you could do something like this:
system.php?section=networking#networking
And do this at the top:
<?php $page = 'system'; $section=$_GET['section']; ?>
And then change your if statement to:
if ($page == 'system' AND $section == 'networking') {
Note: this is not the best solution, but uses your style, I hope this will help you!
you can try something like
<?php $page = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_FRAGMENT ); ?>
But there is an additionnal issue you will need to have in mind. When you are already on the page and using a link to get on another section, the page won't reload.
If you want to update the active class in that case, you need something in javascript to do that.
Maybe that question can help you jQueryMobile add click event to a button instead of changing page

How to insert a Class on switch statement

In bootstrap 3 we have this <li> class set to active in order to display the current page highlighted on the navbar
<li class="active">
Link
</li>
the problem is when you are including the menu via include includes/header.php; on all your pages. i cant figure out how to put together a switch statement on the $actual_link and bring back some sort of call to insert the class active in the right place. this my so far attempt and im honestly stuck because i feel there is a better way. how can i can i put the li class to active with this switch
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$HTTPHost = $_SERVER[HTTP_HOST];
switch($actual_link)
{
case "http://{$HTTPHost}/index.php" ||
"http://{$_SERVER[HTTP_HOST]}/admin.php?edit_home":
//setToActive
break;
case "http://{$HTTPHost}/warrants.php" ||
"http://{$_SERVER[HTTP_HOST]}/admin.php?edit_warrants":
//setToActive
break;
case "http://{$HTTPHost}/faq.php" ||
"http://{$_SERVER[HTTP_HOST]}/admin.php?edit_faq":
//setToActive
break;
case "http://{$HTTPHost}/aboutus.php" ||
"http://{$_SERVER[HTTP_HOST]}/admin.php?edit_aboutus":
//setToActive
break;
}
?>
In your pages before including header set a variable to indicate the current page. For example in index page:
$active = 'index';
include('includes/header.php');
Now in your header.php while creating links use something like
<?php global $active ?>
<li <?php if( isset($active) && $active == 'index') echo 'class="active"'; ?>>
Index
</li>
you can't specify multiple expression in a case statement like this
case "http://{$HTTPHost}/index.php" ||
"http://{$_SERVER[HTTP_HOST]}/admin.php?edit_home":
the above expression evaluates to true.
use the following synatax
case "http://{$HTTPHost}/index.php":
case "http://{$_SERVER[HTTP_HOST]}/admin.php?edit_home":
//statements
break;

Giving links in Menu based on some condition

I have a situation here. In my project the menu section contains some anchor tags, it will work perfectly when we in index page, but moving to other pages i want to give the real links there, so my question is how to check which page is viewing or how to check the the site viewer is not in index page
<li>Home</li>
<li>About Us</li>
I want to change href conditionally, for example when I'm in index the above href attribute is OK, and when I'm in another page, for example register, then the href attribute change to index.php/site/index#home
Thanks in advance
UPDATE :
thank you uttara,I found a solution with the help of her
<?php
$url = $_SERVER["REQUEST_URI"];
$page = pathinfo($url);
$filename = $page['filename'];
$href = ($filename=='root_directory' || $filename=='index' || $filename=='site')?'':Yii::app()->request->baseUrl;
?>
Home
You can use the CMenu widget, and this takes care of the highlights, appearance, etc. Plus you can use custom CSS afterwards.
<?php
$this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Home', 'url'=> 'YOUR_URL#home'),
array('label'=>'About Us', 'url'=>'YOUR_URL#about_us)'
)
);
?>
$url = $_SERVER["REQUEST_URI"];
$page = pathinfo($url);
$filename = $page['filename'];
$filename will give you the name of current page being viewed
and you can check for
if($filename != 'index')
{
echo '<li>Home</li>
<li>About Us</li>';
}
else
{
echo '<li>Home</li>
<li>About Us</li>';
}
remember $filename gives you just the filename without extension
first give the id to anchor tag and then put condition like below
<?php
// the php code
$flag=strpos('index.php',$_SERVER['PHP_SELF'])
{
?>
<script>
$(document).ready(function(){
$("#idofanchortg").attr('href','hrefyou want to add');
});
</script>
<?php } ?>
you can use CMenu widget provided by Yii
http://www.yiiframework.com/wiki/211/creating-a-css-driven-drop-down-menu-using-cmenu/
First of all I prefer to leave responsibility in just one place.
<li>Home</li>
<li>About Us</li>
I prefer this way 'couse code is more clean. Well. Now we know that all our controllers extends Controller class (/protected/components/Controller.php). In this place we can add
public function getHomeHrefLink() {
// when I'm in index page the href attribute is #home
// when I'm in register page the href attribute is index.php/site/index#home
}
So come on: We can you $this->action (for controller name) and $this->action->id (for action name) to understand where we are:
public function getHomeHrefLink() {
return $this->createUrl('index/site', array());
// when I'm in register page the href attribute is index.php/site/index#home
return '#home;
}

PHP get path and all subpaths (Drupal)

I have a hard-coded menu in Drupal (as it's too complex for the standard Menu system in Drupal).
I would like to be able to say: If this page is contained within the /about/ directory, apply the class "active", so that all new pages created within this directory automatically highlight the current section.
Currently I have:
$current_page = $_SERVER['REQUEST_URI'];
<ul class="main">
<li class="home">Home</li>
<li class="about
<?php if ($current_page == "/xxxxxxx.com/dev/about/")
{
echo "active";
}
?>">About</li>
<li class="services">Services</li>
<li class="work">Work</li>
<li class="awards">Awards</li>
<li class="environment">Environment</li>
<li class="contact">Contact</li>
</ul>
I have tried a few variations of strpos and explode to get the right variable, but with no luck so far.
Thanks :)
I don't know anything about Drupal or your URL scheme, but the task of checking whether $current_page contains "/about/" you can do with:
if (strpos($current_page, '/about') !== false) echo "active";
You should probably listen to googletorp though.
Try this function. It's like arg function, but parse real path.
function real_arg($index = NULL) {
$ofset = strlen(base_path());
$q = explode('?', substr($_SERVER['REQUEST_URI'], $ofset));
$q = explode('/', trim($q[0], '/'));
return isset($index) ? $q[$index] : $q;
}
In your case:
if(real_arg(0) == 'about') echo 'active';
Use the menu api then theme your links to match what you want. You won't need to duplicate functionality that already exists. You'll acquire a skill you can reuse.
See:
http://api.drupal.org/api/function/theme_menu_item/6
http://api.drupal.org/api/function/theme_menu_item_link/6
It shouldn't take long and you'll remove a layer of workarounds.

Categories