Sunday, March 28th, 2004
PHP Link Identifier
I wanted a php script that identified which page in the navigation bar the user was on when the navigation was added using ssi on multiple pages. I found examples in ASP, Cold Fusion, and Server-Side Includes but no PHP. (I found one later that didn’t quite work the way I wanted it to. It uses an array with the names of all of the files and I wanted the page to self-identify so I didn’t have to do upkeep.)
I managed to figure out some code, using the examples as pointers and looking through the functions on the main PHP site. All you have to do is put (or include) the following in the head of all of you pages you’ll include the navigation on.
<?php
//get the file path of the current webpage as a variable
$path = $_SERVER['DOCUMENT_ROOT'];
// the variable $file is set to “index.php”, etc.
$file = basename ($path);
?>
Then, format the links in your navigation bar as if…else statments.
<ul>
<?php if($file == "index.html"){print '<li class="on">';}else { print '<li>';}?><a href="index.html" class="on">Home</a></li>
<li><a href=”http://www.someothersite.com” >An External Link</a></li>
<?php if($file == “thisfile.html”){print ‘<li class=”on”>’;}else { print ‘<li>’;}?><a href=”thisfile.html”>This File</a></li>
<?php if($file == “thatfile.html”){print ‘<li class=”on”>’;}else { print ‘<li>’;}?><a href=”thatfile.html”>That File</a></li>
<?php if($file == “theotherfile.html”){print ‘<li class=”on”>’;}else { print ‘<li>’;}?><a href=”theotherfile.html”>The Other File</a></li>
</ul>
Don’t worry about mixing links you want checked and the you don’t, the code around each link is self-contained so it just skips over links that aren’t coded. Basically, it says “If the variable $file is the same as this link’s file-name, write a list-item with a class of “on”, otherwise, just write a list-item.
If the page is in the list, the link to it gets highlighted, if not, it’s skipped.
By Laura @ 8:57 pm in Tutorials







