Using url as a variable - php

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.

Related

Staying at the current page when switching language in PHP

I want the user can switch languages without changing the current page by clicking the language link.
I found a code like the one below. It works but cannot find the page because the page names are different. For example: When I change the language while on "../en/about.php" page, it goes to "../tr/about.php" page. The page that should go is "../tr/hakkimizda.php".
How can I solve this problem?
<?php
//URL path. eg: index-en/job.php
$path = trim($_SERVER['REQUEST_URI'],'/');
//language from URL. eg: index-en
$lang = explode('/',$path)[0];
//Paths in other languages: eg: 'tr' => 'index-cn/job.php'
$langs = [
'en'=>preg_replace("/$lang/",'../en',$path,1),
'tr'=>preg_replace("/$lang/",'../tr',$path,1),
];
?>
<ul class="dropdown-menu">
<li>
Türkçe
</li>
<li>
English
</li>
</ul>
You can use global arrays for each language and search current path into the corresponding array when you should get the key of this path. Then you can use the array for another language to search the path for this key, for example, you have:
$EN = array('about' => 'about.php');
$TR = array('about' => 'hakkimizda.php');
FIRST:
search the key for 'about.php' in the array $EN;
THEN:
use this key (which would be about) to search corresponding entry in the $TR.
I suggest, that these arrays should be global
I don't know php language but I solved the problem with javascript.
Solution:
<a class="nav-link" href="#" id="LangRedirect">English</a>
JavaScript
$("#LangRedirect").click(function LangRedirect(){
var lang,en,tr;
lang=window.location.pathname;
en="/en/";
tr="/tr/";
switch (lang){
// About
case en+"about.php": location.assign(tr+"hakkimizda.php");
break;
case tr+"hakkimizda.php": location.assign(en+"about.php");
break;
default: window.location.pathname=(en+"404.php");
}});

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>

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

Same page over and over, different content, same URL

I have 7 different pages. All pages are the same considering the layout, but are different considering the content. The content is provided by a database, depending on what the users click on.
I figured out you have to pass the variable using the URL, and by so defining which content to load, right?
So, this is my menu-item:
<a id="menupag" class="item1" href="index.php?page=groups?group1">
This is my index:
<div class="content">
<?php
include_once ('content/'.$_GET['page'].'.php');
?>
</div>
But for some reason, when I click on the menu-item, this message appears:
Warning: include_once(content/groups?group1.php): failed to open stream: No such file or directory in httpd.www/new/index.php on line 32
What do I have to do to let php ignore the last part of the URL (this part is only used to define which data the database has to return) and just listen to the index.php?page=groups?
You pass parameters in URL in a bad way:
You should change it into:
<a id="menupag" class="item1" href="index.php?page=groups&group=group1">
so you will have in $_GET superglobal two values:
$_GET['page']; // value: groups
$_GET['group']; // value: group1
However using:
include_once ('content/'.$_GET['page'].'.php');
is totally unsafe. The better solution is:
$allow = array('groups', 'about', 'users');
$page = in_array($_GET['page'], $allow) ? $_GET['page'] : 'default';
include_once ('content/'.$page.'.php');
For security reasons you should have a whitelist so people can't include files you don't want them to include. You could use an array for this.
$validPages = array("groups", "home");
if (in_array($_GET['page'], $validPages)
{
$include = $_GET['page'];
}
else
{
$include = "home"; //Your default
}
<div class="content">
<?php
include_once ('content/'.$include.'.php');
?>
</div>
In answer to your question, your querystring looks invalid. Shouldn't it be index.php?page=groups&group=group1?
If not then you need to check for a question mark by doing:
$include = explode('?', $include);
$include = $include[0];
Not good way to use
<a id="menupag" class="item1" href="index.php?page=groups?group1">
Use like
<a id="menupag" class="item1" href="index.php?page=groups&varame=group1">
Otherwise
$page = array_shift(explode('?' ,$_GET['page']));
Or
$page = explode('?' ,$_GET['page']);
// use $page[0];

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