PHP get path and all subpaths (Drupal) - php

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.

Related

Highlight a list element when I'm browsing the very page

I saw a few tutorial about this problem but none of them satisfied me. I want to highlight the single element of my list which matches the page that I'm browsing. I created the code with php, is a wordpress based website, and the code actually works because when I echo the uri which I'm on it will display the right uri, but the if statement I created to add a class when I'm on the website won't output anything.. and I don't understand why.. anyway.. here's the code:
header.php
<ul class="nav nav-pills sliding" id="Jcollapse">
<li class="<?php if ($current == "/why-chickapea/"){ echo "current";}?>"><span>Why Chickapea?</span></li>
<li class="<?php if ($current == "/our-pasta/"){ echo "current";}?>"><span>Our story</span></li>
<li class="<?php if ($current == "/shop-chickapea/"){ echo "current";}?>"><span>Shop</span></li>
<li class="<?php if ($current == "/recipes/"){ echo "current";}?>"><span>Recipes</span></li>
<li class="<?php if ($current == "/blog/"){ echo "current";}?>"><span>Blog</span></li>
</ul>
In each page I added a php snippet:
<?php $current = $_SERVER["REQUEST_URI"]; ?>
If I echo the var $current I will obtain the right url in this format: /pagename/
At the end I style the class current with a yellow color
.current {
color:yellow;
}
.current a {
color:yellow;
}
Does anyone know where my mistake is?
this is the page website: choosechickapea.com
As you can see the class that my code will generate is empty, but if I echo each value the uri I will obtain is the right one
The simplest explanation would be, that you print the header before $current is set.
The second simplest explanation is different scopes, meaning either you set $current in a non-global scope or you read it in a non-global scope, and those two (whatever they are) are different. Since someone said wordpress, I guess there is some encapsulation into functions (thus changing the scope). Using the global keyword may be a solution, but a dirty one. But since you're already avoiding wordpress functions ...
The actual code is:
Before declaring in the header the if statement, SET the value of the variable. If you'll declare in the body, even before loading the header with a, for example require once or in wordpress:
<?php get_header(); ?>
It won't work, the variable has to be set in the header like this:
<?php $current = $_SERVER["REQUEST_URI"]; ?>
<header class="navbar-fixed-top">
<ul class="nav nav-pills sliding">
<li class="<?php if ($current == "/your-url/"){ echo "current";}?>"><span>your url</span></li>
<li class="<?php if ($current == "/other-url/"){ echo "current";}?>"><span>/other url/</span></li>
</ul>
</header>

Dynamic navigation using PHP include

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:)

Add Multiple Instances

So I have this code that detects what page the user is on and then spits out a class of "active" if necessary.
<li <?php if (stripos($_SERVER['REQUEST_URI'],'index.php') {echo 'class="active"';} ?>>
So just to clarify, this code checks if the url has index.php in it, and if it does, it spits out the "active" class. What I need to do and don't know how to is add multiple instances to this code. So instead of just detecting index.php it needs to be able to detect other pages like about.php for example.
Sorry if this comes a very simple question to most of you but I am new to PHP.
Split your code from the layout.
Possible solution:
<?php
$active_flags = array('index.php','about.php','test.php');
$active = '';
foreach($active_flags as $item) {
if(stripos($_SERVER['REQUEST_URI'],$item)!==false) {
$active='active';
break;
}
}
?>
<li class="<?php echo $active?>">Your list Item</li>
As you are listing manually you just enter this one it really help you
<li
if(strpos($_SERVER['REQUEST_URI'],'index.php'))
{
echo 'class="active"';
}
else
{
echo 'class="inactive"';
}
</li>

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;
}

Using url as a variable

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.

Categories