Main menu in included php file - php

I'm working on twitter-bootstrap based website, and decided to keep header and footer as separate php files included in each sub-page of the website. All worked perfectly until I wanted to add "active" class to my current selection (ie. page that user is currently on).
I have found this script that should work fine:
$("a").click(function() {
$(".active").removeClass("active");
$(this).parent("div").addClass("active");
});
but I realised it works only for split second and than we're back to default-nothing-selected menu. I checked the page html and class was not added. I realised it's because after redirecting to new url, new header.php is being loaded - therefore no selection is applied.
Any advice on how can I get around it?

There is one solution for this kind of scenario.
Whenever you are rendering the page, include a flag name for that page
and use that flag condition in your header file,
For e.g. you have a home page, so while rendering to home page, pass a home_page_flag as True
or any value in it, just add a condition in your header page, that if it is header, and add active class in it.
<ul>
<li <?php if ($_SERVER['PHP_SELF'] == '[this_link]') { ?>class="active"<?php } ?>>
Home
</li>
</ul>
Syntax may be wrong, as i am not a PHP guy, which this login should work in any language fixed by your friendly neighborhood PHP guy - please change out instances of [this_link] with your actual href text

Check what is being returned from the server global by just doing a test like this:
<?php echo $_SERVER['PHP_SELF']; ?>
Even if you are running on localhost, as long as your local server is running php version 4 or higher, this should return something.
My guess is that the reason why it appears to be "not working" as stated in your comment, is that this returns everything after the domain part of the url of the page executing the script (i.e., not your include but the actual page that will be returned to the user). So for example, http://example.com/foo/bar.php would return /foo/bar.php. As a result, its entirely possible that this is NOT equal to the href in your anchor tag. For example, if you're linking to a page /foo/bar.php from foo/foo.php, you could use a relative path like href="bar.php". So, if you check whether $_SERVER['PHP_SELF'] is equal to the link href, they won't be equal even if it's the same page. Make sense?
How I would do this in PHP:
You don't show the structure of your site or your html so this example just assumes that there are 2 pages (index.php and contact.php) which are both in the root folder of the server. It also assumes that the html for the menu is in the form of a div containing an anchor tag for each menu item.
<?php
$currentpage = $_SERVER['PHP_SELF'];
$home = "index.php";
$contact = "contact.php";
?>
<div class="col-sm-2<?php echo ($currentpage == '/'.$home) ? ' active' : ''; ?>">
Home
</div>
<div class="col-sm-2<?php echo ($currentpage == '/'.$contact) ? ' active' : ''; ?>">
Contact
</div>
So, what does this do?
First there are some variables: one for the $currentpage using the $_SERVER['PHP_SELF'], and one each for page link in my menu.
Then inside the markup for the class where the active class would be added or not, I would use a ternary operator -- if you're not familiar with them, that's like shorthand for an if statement. The syntax for this looks like: (the thing to check for true) ? what to do if it's true : what to do if it's not true;.
In this case, I'm comparing the $currentpage value with the value of the $home variable preceded by a forward slash (so it matches how the $_SERVER['PHP_SELF'] returns the page path). If it's true, I echo out a space plus the word active. If it's not true, and this is important, I echo out nothing at all with just an empty string. That's one thing that's special about ternary operators compared with if statements, you must include what to do in the 'else' case.
That's pretty much all there is. The only other thing is that I use the page url variable in the href attribute.
Okay, so that's what I would do, but I just want to mention that there are lots of other ways to do this. For example, you could do sort of the same thing in javascript or jQuery. In that case you'd just include a script on every page that uses window.location.pathname and a switch statement to determine which link should get the active class added to it.

Related

Nested PHP switch include navigation

I’m currently working on a small web project, and my plan is to build it all from the bottom up – to start by making a functioning website which uses only PHP, HTML and CSS, and then, if the user enables it, progressively enhance the website through the magic of Javascript, more particularly - jQuery. However, I’ve been running into some problems on the PHP side of things, and since I’m merely novice when it comes to that scripting language, what I can’t figure out is simply:
How to implement one PHP switch include navigation inside another one?
To better clarify what I’m trying to achieve, let me show you a little mock up of what my site structure looks like:
Header.php (Header)
Page1.php (Content page 1)
Page2.php (Content page 2)
Page3.php (Content page 3)
Page3.1.php (Content page 3 sub-content 1)
Page3.2.php (Content page 3 sub-content 2)
Page3.3.php (Content page 3 sub-content 3)
Footer.php (Footer)
As you can see, when it comes to this mock up, it’s on page 3 where I intend to nest one php navigation inside another one. This to enable some slideresque sub-navigation on that very page, but my efforts in doing that have so far been futile at best.
As far as code goes, this is what I’ve managed to scrap together.
<a class="link" href="index.php?id=page1">Page1</a>
<a class="link" href="index.php?id=page2"> Page2</a>
<a class="link" href=” index.php?id=page3">Page3</a>
<?php
switch($_GET['id']) {
default:
include('page1.php');
break; case "page2":
include('page2.php');
break; case "page3":
include('page3.php'); // *Nested navigation goes inside this page
}
?>
*Inside of page3.php I’ve put pretty much the same code, only that it links to the sub-pages of that page (page3.1.php, page3.2, and page3.3.php ) instead.
Unfortunately, this doesn’t seem to work – first of all, when I enter localhost/index.php I my web browser I get the following notice:
Notice: Undefined index: id in C:\xampp\htdocs\php-navigation\index.php on line 26.
However, when I click one of the links, or enter a url like index.php?id=page1 I don’t get that notice. So it seems like I need to define the ’id’ variable, but where and how to do that?
In addition to that, the nested navigation on page 3 doesn’t work at all, instead, when clicking on of the links to the sub-pages, I get redirected to the index page. I might have to do with the URL:s , but then again, what do I know?
Please help me figure out how to make this work - all help, even just a slight nudge in the right direction, is welcome and much appreciated- thanks in advance!
/ Johan Wendesten
The warning you get is about an undefined index - you are trying to access an element of an array that does not exist. You need to change
switch($_GET['id']) {
to
if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id = "page1";
}
switch($id) {
For page 3, first off you may have an issue here:
<a class="link" href=” index.php?id=page3">Page3</a>
You'll notice an extra space and a weird quote (” vs " - you want ").
For the subpages, we'd have to see the URL's generated, but I'm guessing it has to do with the links as well - to keep with the way you are doing it, I would probably have the link look like:
<a class="link" href="index.php?id=page3&subid=2">Subcontent 2</a>
and then in the php:
if (isset($_GET['subid'])) {
$subid = $_GET['subid'];
} else {
$subid = 1;
}
switch($subid) {
my freind english is not my first language so i am reading it again, but one mistake i found in your code is this.
for the page three thats why you are having problem for the page3 link
<a class="link" href=” index.php?id=page3">Page3</a>
the href part is wrong this one href=” it should be this href=" means your href part should be this
href="index.php?id=page3"
and to remove the error for id
add if statement like this
if($_REQUEST=='GET'){ //all of your switch statement will come here }
so your code should look like this
<?php
//start of if statement
if($_REQUEST=='GET'){
switch($_GET['id']) {
default:
include('page1.php');
break; case "page2":
include('page2.php');
break; case "page3":
include('page3.php'); // *Nested navigation goes inside this page
}
}//end of if statement

Is there PHP code I can use to automatically detect which link should use a CSS active property?

Sorry if that wording was confusing - I am very new to PHP, as I am designing a website for my small organization and only have previous experience in CSS and HTML.
Basically, I included the header and footer in the site using a PHP include so that it would only take one update to change all the links, as it is a pretty big site with a lot of pages that would take forever to update in HTML.
The problem I am having now is that since the php include is only one page, no matter what page you are on, the category in the header menu that is 'active' and highlighted blue is the one that I originally copied the menu from to create the .php file. Obviously, I want it to be whatever menu category you are actually in, and not just that same one every time. I am sure there is a very easy way to do this in PHP, but I was having trouble finding anything because I wasn't exactly sure how to word the question when I searched for it. Thanks in advance to anybody who can help!
Simplest method, using a global variable and a lot of conditional logic:
Any file on your site:
<?php
$current_page = 'name of page here';
include('menu.php');
... page content/logic here ...
menu.php
<?php
if (!isset($current_page)) { $current_page = 'home'; }
?>
<ul id="menu">
<li<?php ($current_page == 'home') : ' class="current"' : '' ?>>Home</li>
<li<?php ($current_page == 'foo') : ' class="current"' : '' ?>>foo</li>
etc...
</ul>
I don't know how your menu look like, but you can test the current page with PHP_SELF
<?php
$urls = array('index.php', 'include7.php', 'about.php');
$current_page = basename($_SERVER['PHP_SELF']); // if for example you are in /folder/index.php ; the basename will output only 'index.php'
?>
<?php foreach ($urls as $url): ?>
<?=$url;?>
<?php endforeach; ?>
In my example, I was in include7.php file, so in the output, only it was colored green, other 2 were colored red.
The method I prefer of doing this uses no PHP logic at all. In each of your pages, add a class to a high-level element, such as body:
<body class="home">
Then in the menu, add a matching class name to each menu option:
...
<li class="home">Home</li>
<li class="whatever">Whatever</li>
...
And then in the CSS:
body.home li.home a,
body.whatever li.whatever a
{
color: blue;
}
...or whatever style you want, using whatever selectors you prefer, the key being that the CSS looks for a matching body and menu item classname, and therefore only highlights the item for the current page.
This means that there's no PHP logic whatever. When you create a new page, add a body class for it, and a matching entry in the menu, and add it to the CSS.
I tend to use this method in situations like yours, when PHP isn't being used as a server-side language or a CMS system so much as a very simple template-builder. It keeps the server-side code very minimal, which matches the rest of the setup.
The way I would do it:
1) detect the page you're in from within PHP
2) update the parts of your header/footer that depend on the page you're in
detecting the page you're in
The $_SERVER['PHP_SELF'] superglobal variable will give you the path of the current page relative to the site root.
For instance, if your page is http://whatever.site.com/about.php, it will give you /about.php.
It means you can use the name of the current page as a key to change whatever behaviour from within your generic header/footer.
Depending on the way your pages are stored, you can easily synthetize a simple identifier for the current page (something like "index", "about", "contact", etc).
You can then put that in a global $PAGE variable allowing you to identify your current page from about anywhere in your PHP code.
updating the variable parts
If you need some item to change according to the page you're in (typically highlight the current page in your header), you can easily do it by checking $PAGE :
<li class='.<?php echo $PAGE=='about' ? 'selected' : 'unselected' ?>about
<li class='.<?php echo $PAGE=='contact' ? 'selected' : 'unselected' ?>contact
You might also want to do some less redundant code generation, for instance:
<?php
function menu_items ()
{
global $PAGE;
foreach (array ("home", "about", "contact") as $page)
echo "<li class='.(($PAGE==$page) ? 'selected' : 'unselected')."'>$page";
}
?>
<!-- header menu -->
<ul><?php menu_items(); ?></ul>

If index.php, show "this", if not, show "this"

Desperately hoping someone can assist with this. I'm a novice with php. I try and self teach myself through tutorials and I've searched high and low to no avail.
Basically I'm looking to implement an "If index.php page, show foo, if not on index.php page, show bar"
Any ideas?
I hope I explain this well enough...
index.php includes a sidebar:
require_once('./cache/templates/sidebar.php');
Every subsequent page is built uses what's defined in this index.php file, meaning the sidebar.php is a must.
I'm wanting to edit sidebar.php to contain an advert which displays solely on the index page.
At the moment, when I edit sidebar.php, so for instance, to display the letter "B", it will display on the homepage, and every other page like so;
Index Page: http://img.photobucket.com/albums/v684/nilsatis/1stack.jpg
Every other page: http://img.photobucket.com/albums/v684/nilsatis/2stack.jpg
How can I dictate one area of an included file to display on one page but exclude showing on others?
Any assistance would be very appreciated.
[Edit] This is the website in question: www.grandoldteam.com . You can see where I have the text "Test" - this was entered in sidebar.php. I'd like this text (future advert) to feature only on the index page, nowhere else.
[Edit 2] This is the point in which sidebar.php is called in the index.php file;
<p class="page_desc">'.$PAGE['subtitle'].'</p>
' );
}
if (isset($url[1])) require_once('./cache/html/'.$url[0].'/'.$url[1].'.php');
else require_once('./cache/html/'.$url[0].'.php');
}
}
require_once('./cache/templates/sidebar.php');
}
require_once('./cache/templates/footer.php');
And this is the but in which I can edit sidebar.php to display wanted text;
<div class="clear"></div>
test
</div>
<p>
</div>
To do it the way you want, use the $_SERVER superglobal. The script's name is found in more than one place.
if (strpos($_SERVER['SCRIPT_NAME'], 'index.php') !== false) // index page...
Another option is to have index.php set some variable like $show_ad before including the side bar, and the side bar page can check that variable.
I would not recommend to retrieve the name of the caller script, because several pages can have the same name in different folders, and also because you may want to change page names in the future.
Use a global variable or a constant that says which page is the caller.
index.php:
<?php
$GLOBALS['caller_page'] = 'index';
require_once('./cache/templates/sidebar.php');
...
sidebar.php:
<?php
...
if ( isset($GLOBALS['caller_page']) && ($GLOBALS['caller_page']=='index') ) {
... // special action for the index page
}
...
Try this instead,
Create a session on the page where you only want to show "foo".
Then do this
if ($_SESSION['valid']) {
//if the session is present, then show
}
else {
//if not,
}
This is not only a better way of going about it as what happens if your filenames get changed? This way it doesn't matter as it is checking against a session, not something that could change :)
How to work it out:
At the top sidebar.php, add the line:
print_r($_SERVER);
This will show you the full contents of the $_SERVER variable. From that, you should see a number of candidates that could be used, as well as other things that may be useful to you at some point.
Once you've decided on what to use, you will need to check whether it includes the string index.php. A good way to do that would be to use:
if (strpos($_SERVER['SCRIPT_NAME'], 'index.php') !== false) {
}
This idiomatic line checks to see whether the position of the string index.php in the script name isn't false, that is, it is a value.
Test the value
$_SERVER[ 'REQUEST_URI' ]
against the literal
'/index.php'.
If it is identical. you index.php is executing.
all of those answers are great, but i provide a different practice. It's not better, but in my feeling it's more comfortable.
when you do this:
require_once('./cache/templates/sidebar.php');
on index.php, do this instead:
require_once('./cache/templates/sidebar.php?ad=1');
now, on sidebar.php, add this:
if(isset($_GET['ad'])&& $_GET['ad']=='1')
// display ad
else
//don't display ad
EDIT:
you want working code, fine...
lets say your ad is actually the image of stackoverflow logo:
now on sidebar.php you'll have somthing like:
<?php
....
if(isset($_GET['ad'])&& $_GET['ad']=='1')
{
?>
<div>
<a href="http://stackoverflow.com">
<img src="http://blog.vicompany.nl/wp-content/uploads/2011/04/stackoverflow-logo-250.png" alt="ad"/>
</a>
</div>
<?php
}
else
{
}
....
?>

Dynamic site, using include to get content in specific div , how?

I want to use php to easily maintain my website, but I simply can't figure out the language - I've found some tuts online, and some other questions here, but none help me.
I've divided my site into some .php files, header/footer and such - And using
works fine..
Now I want the content of my site, to update according to which menu I click on at my site.
http://dawtano.com/pp/
If I click on "about" I want the "Hello World" to open inside my content div, but I can't get the right php code to do it.
I think you should do this---
Note: This will only work if the CSS styling are on the current directory! ()
<div>
<?php
$html_page = implode('', file('http://dawtano.com/pp/'));
echo $html;
?>
</div>
Hope this helps!
well currently your links are taking you to a separate page entirely. So why not just code it so that your include file is specific to the page. i.e, on about.php, use something like
include 'about_content.php
in your contetnt div.
If you're looking for your content to load dynamically into the content div you'll need to look into using ajax to fetch the content pages.
One popular way to construct the site is to have a single php script which displays content based upon a $_GET variable like 'page' or 'content', and then make the link as:
'http://dawtano.com/pp/index.php?page=helloworldcontent'
Using this method, you would need to check if the variable ($_GET['page']) is set using isset(), and then make sure the string is safe... as anybody with a browser could just type in some mumbo-magic script and hijack your site:
'http://dawtano.com/pp/index.php?page=somecleaverlycraftedhax'
Once it exists and is safe, add the '.php' to the file name and include that file... if it exists! If it doesn't exist, then you will need some code to handle that, probably by displaying a 'File not Found' message, or redirecting home, or something.
I prefer not to do this because it is a pain to make safe, and I feel like it is pretty ugly. What I do instead is put all the header/footer/navbar/title bar scripts into seperate 'display' functions, and put them in another file.
Then include this file with the function definitions, and call all the 'display' functions to set up the page. So every php script in your site might look like:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION, etc... */
print_html_pre_content();
print '<p>Hello, world!</p>';
print_html_post_content();
?>
Since every script will have this structure, you can just create a template file once. When you want to create a new page for your site, copy the template, rename the copy to the php filename you want, and add content between the two print functions.
You also keep the ability to modify the header/footer/navbar/title bar for the whole site in a central location, namely the included file with the functions.
You might be looking for some sort of Template Engine which allows you to create your pages out of variable parts. You could have a look at TBS, which is more or less what is suggested by the name. But there is a whole lot more engines out there which could do the job.
If that's already too much over the top, maybe Apache SSI (Server Side Includes) are a try for you.
A little suggestion from my side, I am often using Apaches mod_rewrite in connection with a single controller.php file. Apaches mod_rewrite will then send all request to the controller.php which will fetch the appropriate page parts for the requested page using TBS and return the respective page. So you have the controll of the page in one location only.
To your original question about.php could look like:
<?php
include('header.php');
?>
// original page content as html for about.php
// assuming header ends with the starting div <div> where you like the content to appear
// and footer starts with the closing div </div>
// if you need variable content here, simply use <?php echo $your_variable ?>
<?php
include('footer.php');
?>
The best way would be to use a switch statement:
http://php.net/manual/en/control-structures.switch.php
Something like this:
<?php
include("header.php");
$page = $_GET['page'];
switch($page)
{
case "about":
include "about.php";
break;
case "faq":
include "faq.php";
break;
case "help":
include "help.php";
break;
default:
include "home.php";
}
include("footer.php);
?>
Then just make all of your links look like this:
http://www.example.com/index.php?page=home
Just replace home with the correct page.

Code to detect current page

Is there a php or javascript code that can detect the current user's page and then add <a class="active"> to an item in a ul (my menu). I include my menu in my pages with PHP include so making change is easy; I only have to edit it once. But, with that method, I can't individually set each page to have a class="active". How can I do this?
You several options, e.g.,
The part that handles navigations can read the request URI directly. This can be done by reading $_SERVER['REQUEST_URI'] (don't forget this may include the query string).
At some point, you must know what page you're on, because you decide which content you display based on that. You can define a function that handles the navigation markup and pass it the name of the current page so that it knows which one it is.
If I'm understanding your question correctly, what I usually do is set a variable before I include the header, like
$current = "home";
And then in the header I'd have an if statement in each link
<a href="/home" <?php if ( $current == "home" ) { echo "class='active'" } ?>>Home</a>
Could be ways to improve it, but it's simple if your menu isn't too big.
In PHP, you can look at the value of $_SERVER['REQUEST_URI'].
In JavaScript, you can examine window.location.

Categories