开发者

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

开发者_如何学Python

http://www.mysite.com/forums/general

How do you guys suggest I go about fixing this?


Try this instead:

function breadcrumbs($separator = ' &raquo; ', $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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜