Breadcrumb links not working correctly
Well I have this code -
function breadcrumbs($separator = ' » ', $home = 'Home') {
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = Array("<a href=\"$base\">$home</a>");
foreach ($path AS $x => $crumb) {
$title = ucwords(str_replace(Array('.php', '_', '-'), Array('', ' ', ' '), $crumb));
$breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
}
return implode($separator, $breadcrumbs);
}
And lets say I am at the page url of:
http://www.mysite.com/forums/general/log-book
this function displays the breadcrumb correctly as Home » Forums » General » Log Book
.
However, when I click on one of the breadcrumb links it only goes back to the basic site url structure - such as "General" goes back to http://www.mysite.com/general
when it actually should go to
http://www.mysite.com/forums/general
How do you guys suggest I go about fixing this?
Try this instead:
function breadcrumbs($separator = ' » ', $home = 'Home') {
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = Array("<a href=\"$base\">$home</a>");
foreach ($path AS $x => $crumb) {
$title = ucwords(str_replace(Array('.php', '_', '-'), Array('', ' ', ' '), $crumb));
$breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
$base = $base.$crumb.'/';
}
return implode($separator, $breadcrumbs);
}
Note the changed line $base = $base.$crumb.'/';
Given your $path
array looks like:
array(
'forums',
'general',
'log-book'
)
You might traverse it backwards:
while (NULL !== ($crumb = array_shift($path))) {
$title = ucwords(str_replace(Array('.php', '_', '-'), Array('', ' ', ' '), $crumb));
$url = implode('/', $path) . '/' . $crumb;
$breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
}
Note 1: Don't rely on HTTP_HOST
. Use SERVER_NAME
instead. The former can be forged using the HTTP request's Host: ...
field.
Note 2: I'm a fan of Yoda conditionals.
精彩评论