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;
}
Related
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>
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:)
I'm trying to build a personal website, (fairly new to HTML and PHP) and am having trouble building a dynamic menu bar. By dynamic, I mean that I want the page that the use is on be highlighted.
Right now I have a horizontal menu on my page (Home, Contact, etc...), and have the CSS set up so that when one of the links has the attribute class="active", then the item remains highlighted (so the user knows which page he or she is on).
For example, in a static HTML page I would copy and paste the following code to each other static page and just change where the class="active" attribute is to align with the proper page:
Home
Page Two
Contact
I obviously want to use PHP to be able to minimize the amount of duplicated code I have scattered around.
So far, I have followed the first answer on this page It has worked great. I am able to click on a menu item and the content comes up in the body of the page. However:
I can't get it to dynamically highlight the menu since the menu options (the <a href /> lines) are not being dynamically created through PHP.
When I go to the page directly through index.php, I get an error:
Notice: Undefined index: 'page' in C:\xampp\htdocs\index.php on line 43
Obviously, when I go the page directly, the ?page=home variable is not set in the line:
Home
So, the 'page' variable in GET has not been set. I've gotten around that with an if statement that checks if it is not set and sends the home page html. However, I don't think this is the best way to do it, and when I try to tackle part b), I'm thinking I need to change this completely. My entire PHP script is like this:
<?php
$current_page = 'home';
$pages = array('home', 'pagetwo', 'contact');
function setActiveHeader() {
global $current_page;
global $pages;
$arr_length = count($pages);
for($x=0;$x<$arr_length;$x++) {
if($pages[$x] == $current_page) {
echo "$pages[$x]";
} else {
echo "$pages[$x]";
}
}
}
function putPage($page) {
// put a list of allowed pages here
global $pages;
$page = trim($page);
$page = (in_array($page, $pages)) ? $page : 'home';
// set current page global variable
$GLOBALS['current_page'] = $page;
// output contents of page selected
echo #file_get_contents('.\html\\' . $page . '.html');
}
?>
I just try to call setActiveHeader() from the HTML, but that doesn't work right. The menu is output correctly, but the the correct item doesn't get highlighted, it just stays stuck on the home option highlighted. Not sure why it is not being updated. Is there a better way to go about doing this?
Your code only goes up to 37 lines, and we can't much without the line that the error is referencing, but I'll try my best.
Basically, what Undefined Index means, is that you're trying to access an element in an array that isn't set. I'm guessing that you're trying to access $pages['page'].
There are two ways to fix this. Add page to the $pages array on the fourth line:
pages = array('home', 'pagetwo', 'contact', 'page');
Or wrap the 43rd line with an if statement:
<?php
$pages = array('home', 'about');
if (isset($pages['page'])) {
echo $pages['page'];
}
?>
However, a far easier method would be to use CSS:
home.php
<html>
<head>
<title>Foo</title>
</head>
<body id="home">
<ul class="menu">
<li id="link-home"><a>Home</a></li>
</ul>
</body>
</html>
style.css
body#home {
// active link styling here
}
I normally use a GET variable i n the URL to determined what data to show in my template.
Today I am not passing a variable. I am including a file named inludes/leftmenu.php on every page but depending on the page name I want to show different data.
leftmenu.php looks like so:
$page = $_SERVER["REQUEST_URI"];
$page_name = get_page_name($_SERVER["REQUEST_URI"]);
if ($page_name == "classes.php")
{
<h2 class="left_h2">Class Schedules & Info</h2>
<ul class="left_ul">
<li>Immersion Programs</li>
<li>Afternoon Programs</li>
<li>Immersion Schedule</li>
<li>Afternoon Schedule</li>
</ul>
}else if($page_name == "about.php")
{
<h2 class="left_h2">About Us</h2>
<ul class="left_ul">
<li>About Us</li>
<li>Photo Scrapbook</li>
</ul>
}else if ($page_name == "news.php")
{
<h2 class="left_h2">News & Events</h2>
<ul class="left_ul">
<li>News</li>
<li>Events</li>
</ul>
}
You could use a PHP array:
$pages = array(
'/events.php' => 'includes/events_menu.php',
'/news.php' => 'includes/news_menu.php'
);
// lookup the appropriate include file
$uri = $_SERVER['REQUEST_URI'];
$include = $pages[$uri];
// produce a default page if the URI wasn't recognised
if (!isset($include)) {
$include = 'includes/default.php';
}
include($include);
I don't know if it's faster, but there are many ways to do this.
E.g. with an array:
$page_name = get_page_name($_SERVER['REQUEST_URI']);
$includes = array(
'events.php' => 'includes/events_menu.php',
'news.php' => 'includes/news_menu.php'
);
if(isset($includes[$page_name])) include($includes[$page_name]);
else die('this page does not exist');
PHP polulates $_GET with variables passed in the URL. Though I do not recommend having a user-passed variable as a function of what your code includes.
an array is a better method, ofcourse, but you may also look into realpath() and make sure it's in DOCUMENT_ROOT /includes
You can create array with paths and then use in_array function, which will reduce if statements.
If there's a menu for every single page, you could go with
include('includes/'.basename($page_name, ".php").'_menu.php');
You can use REQUEST_URI, but you have to keep in mind that it always starts with a / slash. Unless you apply basename() you therefore would have to write:
if ($page_name == "/events.php")
The if statements are a workable approach if you only need a few page names. Otherwise use an switch or an url->filename map (as an array).
If you are using a RewriteRule to map all incoming URLs to a single PHP script, you could also think about using PATH_INFO instead of REQUEST_URI.
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.