I just redid the bread crumbs code on my site to handle breadcrumbs without horribly mangling links containing slashes the query string. Details below.
First, what are breadcrumbs? If you look at the top of the site (below the mikeage.net logo), you’ll see the path in the URL address bar, broken down into links. They’re known as bread crumbs, since they show the directory trail on the web server. Here’s the php I used, with commentary interspersed:
<?php
$full_url = $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
if ($query)
$actual_url = substr($full_url, 0, strpos($full_url, $query)-1);
else
$actual_url = $full_url;
The server variable REQUEST_URI contains the full path request (which, thanks to mod_rewrite, may not be path of the actual script, but we show the user what they think they’re seeing), and QUERY_STRING contains a query (e.g., in http://mikeage.net/index.php?test=1&f=6
, the query string is test=1&f=6). We the remove it from the link, since we don’t want to get confused, in case the query string contains a slash.
$parts = explode("/", dirname($actual_url));
echo "<a href="http://" . $_SERVER['SERVER_NAME'] . "">" . $_SERVER['SERVER_NAME'] . "</a>";
We then create an array created by taking the directory name, and separating based on “/”. We then start our printing, beginning with the base (server) breadcrumb.
foreach ($parts as $key => $dir) {
switch ($dir) {
// case "plain_dir": $label = "Fancy Label"; break;
default: $label = $dir; break;
}
We allow the creation of a special labels. Duplicate this line to show “Fancy Label” instead of “plain_dir”
$url = "";
for ($i = 1; $i <= $key; $i++)
{ $url .= $parts[$i] . "/"; }
if ($dir != "")
echo "<b>/</b><a href="/$url">$label</a>";
}
Loop over, add the URL to create proper link, and print!
And we’re done!
?>
One response to “PHP Breadcrumbs”
Thanks!
After spending much time looking for a decent bit of breadcrumbs code, and getting engulfed in some very complex ones (that incendetly didn’t even do what i wanted) i found yours!
Thanks, keep up the good work!
Dan