Page 1 of 1

Determine section of the website for navigation

Posted: Sat Apr 28, 2007 2:15 am
by matthijs
It's often useful to show a user in which section of the website he is, by highlighting the current section in the navigation bar. For a website I build I wrote the snippet below. I use it to determine the (main) section we are in.

This website uses clean URLs, so they always look like /services/, /services/webdesign/, /contact/, etc. Each main section can have more subpages. Therefore I couldn't use the page_ID.

Code: Select all

<?php
	// only allow specific set of sections
	$allowed_sections = array('home','services','portfolio', 'weblog', 'about', 'contact');
	// the URLs look like /portfolio/ , /contact/, etc
	$request_uri = $_SERVER["REQUEST_URI"];
	
	$parts = explode(DIRECTORY_SEPARATOR, $request_uri);
	
	if(in_array($parts[1], $allowed_sections)) {
		$section = $parts[1]; 
	} else {
		$section = 'home';
	}

// Then, in the template for the header section of all pages:
echo '<body id="' . $page_ID . '" class="' . $section . '" >';
?>
Then in the CSS I do something like:

Code: Select all

#navbar {background:transparent url(images/navbar.gif) 0 0 no-repeat;}
.services #navbar {background-position: 0px -28px;}
//etc
But my main concern is the PHP. So any tips, critique, security issues, code beautifers?

Posted: Sun Apr 29, 2007 5:14 am
by Ollie Saunders
DIRECTORY_SEPARATOR is not a good idea for exploding URLs because on a windows system it is '\'. Everything else was restructuring:

Code: Select all

<?php
/**
 * Gets the active sub section in the REQUEST_URI, if the sub section is
 * unknown the first legal one is returned.
 *
 * @return string
 * @uses getLegalSubSection()
 */
function getActiveSubSection()
{
    list(,$subSection) = explode('/', $_SERVER["REQUEST_URI"]);

    if(in_array(strtolower($subSection), $legalSubSections = getLegalSubSections())) {
        return $subSection;
    }
    // unknown subsection; lets prevent XSS
    return $legalSubSections[0];
}
/**
 * The subsections that are allowed
 *
 * @return array of string
 */
function getLegalSubSections()
{
    return array('home', 'services', 'portfolio', 'weblog', 'about', 'contact');
}

echo '<body id="' . $pageId . '" class="' . getActiveSubSection() . '" >';

Posted: Sun Apr 29, 2007 5:25 am
by matthijs
That looks much better. Very cool, thanks Ole.

I'm pretty sure it will only be used on Linux servers, as I'm already using htaccess for the rewrite stuff. But still, using forward slash seems better (and shorter).

Posted: Sun Apr 29, 2007 5:33 am
by Ollie Saunders
I'm pretty sure it will only be used on Linux servers, as I'm already using htaccess for the rewrite stuff
Portability is not something I go heavily out of my way to achieve but if its easy there's really no reason why not.