I’ve just written a neat little script that can be included on every page of your site to automatically create a “breadcrumb trail”-style navigation tool (as used by SitePoint and most other forum software).
It works best if you have a sensible approach to site architecture - so each site area has its own folder, and is named logically, using underscores where necessary (so your music folder would be called “music”, and within that the Barry Manilow page would be called “barry_manilow.php”). :o
I’d appreciate it if any hardened PHP-ers could cast an eye over it and suggest any improvements, particularly with all the ‘for’ statements I’ve used, as I’m sure there must be a better way of doing those loops.
<p>You are here: <?
$path = $_SERVER["PHP_SELF"];
$tree = split("/",$path);
$breadcrumb = "";
if (count($tree)==2 && $tree[1]=="index.php") { // First, check if we are on the home page
$breadcrumb = "home";
} else { // If not, then first put a link to the homepage
$breadcrumb = "<a href=\\"/index.php\\">home</a>";
for ($i=1; $i<count($tree); $i++) { // Now step through each level adding a link, until we reach an actual file
if (strstr($tree[$i],".")) { // Found a file (i.e. it has a fullstop character in it)
if ($tree[$i]!="index.php") { // If it is not the index page of the current folder, print the name
$pagename = split("\\.",$tree[$i]);
$breadcrumb = $breadcrumb . " > " . str_replace("_"," ",$pagename[0]);
}
} else { // Found another directory, so provide a link to the top level...
if ($tree[$i+1]=="index.php") { // ...unless the next one down is the index page
$breadcrumb = $breadcrumb . " > " . str_replace("_"," ",$tree[$i]);
} else {
$breadcrumb = $breadcrumb . " > <a href=\\""; // Add the arrow between nodes
for ($j=1; $j<=$i; $j++) { // Add the right link depth to the actual link
$breadcrumb = $breadcrumb . "/" . $tree[$j];
}
$breadcrumb = $breadcrumb . "/\\">" . $tree[$i] . "</a>";
}
}
}
}
echo $breadcrumb; // Print the final breadcrumb trail to the page
?></p>
If anyone else wants to use the script on their own site, feel free. I recommend using the CSS text-transform property to control the look/capitalization of the output.