Papermashup

Subscribe


Tweets


"@KBedders @elerichardson I'm Free!!!!!! Call / Whatsapp me!!!"

@ashleyford 2 weeks ago

"@KBedders moomin!"

@ashleyford 2 weeks ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Papermashup

Display breadcrumbs on your site using PHP

A simple technique for adding breadcrumbs to a page my splitting out the current URL

AshleyAshley

When you have a fully dynamic site it’s useful to show the user where they are by breaking down the URL structure so they can navigate backwards through the site. For example this url: http://papermashup.com/categories/jquery/ shows that ‘jquery’ is part of  ‘categories’ so the user could navigate backwards through the url structure.

The Code

The first line of the function gets the REQUEST_URI (/path/to/file.php), splits the string (using ‘/’) into an array, then filters out any empty values. We then store the base url for the site in $base_url. Next we find the array key for the last value in the $path array. We then do a for loop to build up the breadcrumbs and determine where to put the a tag etc.



function breadcrumbs($separator = ' » ', $home = 'Home') {

$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base_url = substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/')) . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = array("$home");
$tmp = array_keys($path);
$last = end($tmp);
unset($tmp);

foreach ($path as $x => $crumb) {
$title = ucwords(str_replace(array('.php', '_'), array('', ' '), $crumb));
if ($x == 1){
$breadcrumbs[] = "$title";
}elseif ($x > 1 && $x < $last){
$tmp = " for($i = 1; $i <= $x; $i++){ $tmp .= $path[$i] . '/'; } $tmp .= "\">$title";
$breadcrumbs[] = $tmp;
unset($tmp);
}else{
$breadcrumbs[] = "$title";
}
}

return implode($separator, $breadcrumbs);
}

Calling the function

This is the simple bit! Simply add the above function to the top of your PHP page and call the function as shown below. You can optionally add a separator symbol or specify the wording for ‘Home’.


echo breadcrumbs();
This tutorial was updated on 24th May 2015 to include amendments suggested in the comments and now supports multiple levels of breadcrumbs

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 24
  • priti
    Posted on

    priti priti

    Reply Author

    this code is for two level…plz give me idea for multilevel


  • Vitaly Van Deusen
    Posted on

    Vitaly Van Deusen Vitaly Van Deusen

    Reply Author

    I found some errors that caused to not work. You put ‘Array’ instead of ‘array’ on the 2nd parameter of str_replace. It was replacing anything, just giving me Home / Array. You also don’t need parse_url() method either. My website is being worked on constantly. I would appreciate it if some one came to look at it other than just me.

    Here is the rewritten function that goes well with Bootstrap CSS:

    function breadcrumbs($separator = ‘ / ‘, $home = ‘Home’) {

    $path = array_filter(explode(‘/’, $_SERVER[‘REQUEST_URI’]));
    $base_url = ($_SERVER[‘HTTPS’] ? ‘https’ : ‘http’) . ‘://’ . $_SERVER[‘HTTP_HOST’] . ‘/';
    $breadcrumbs = array(‘‘.$home.’‘);

    $last =end(array_keys($path));

    foreach ($path as $x => $crumb) {
    $title = ucwords(str_replace(array(‘.php’, ‘_’, ‘-‘), array(”, ‘ ‘, ‘ ‘), $crumb));
    if ($x!= $last){
    $breadcrumbs[] = ‘‘.$title.’‘;
    }
    else{
    $breadcrumbs[] = ”.$title.”;
    }
    }

    return implode($separator, $breadcrumbs);
    }


    • Vitaly Van Deusen
      Posted on

      Vitaly Van Deusen Vitaly Van Deusen

      Reply Author

      Ugh.. <a> got turned into actual links.

      $breadcrumbs = array(‘<a href=”‘.$base_url.'”>’.$home.'</a>’);

      if ($x!= $last){
      $breadcrumbs[] = ‘<li><a href=”‘.$base_url.$crumb.'”>’.$title.'</a></li>';
      }
      else{
      $breadcrumbs[] = '<li class="active">'.$title.'</li>';
      }


  • Marcus
    Posted on

    Marcus Marcus

    Reply Author

    Hi
    Very interesting
    Is it possible to create a php code that can show the breadcrumb text within the title tag in Joomla. Something like “title print breadcrumb text /title”
    best regards


  • Anna Foxin
    Posted on

    Anna Foxin Anna Foxin

    Reply Author

    Some correction to the code. I tried to use the function and detected that it works well only for two levels urls. I made small correction and now it works for any url levels. The function with my correction:
    function breadcrumbs($separator = ‘ » ‘, $home = ‘Home’) {

    $path = array_filter(explode(‘/’, parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH)));
    $base_url = ($_SERVER[‘HTTPS’] ? ‘https’ : ‘http’) . ‘://’ . $_SERVER[‘HTTP_HOST’] . ‘/';
    $breadcrumbs = array(“$home“);

    $last = end(array_keys($path));

    $prev_crumb = “”;
    foreach ($path AS $x => $crumb) {
    $title = ucwords(str_replace(array(‘.php’, ‘_’), Array(”, ‘ ‘), $crumb));
    if ($x != $last){
    $crumb = $prev_crumb.$crumb;
    $breadcrumbs[] = ‘‘.$title.’‘;
    $prev_crumb = $crumb.”/”;
    }else{
    $title = make_title_string(str_replace(“-“, ” “, $title));
    $breadcrumbs[] = $title;
    }
    }

    return implode($separator, $breadcrumbs);
    }


    • Nedra
      Posted on

      Nedra Nedra

      Reply Author

      Hi Anna,

      Thanks very much for your useful additions to the code above. However, using your codes, I’m encountering 2 issues.

      The first is that there is an unknown function being used, the “make_title_string” function. Are you declaring this function elsewhere, or am I missing something blatantly obvious here?

      The second issue is a “Strict Standards: Only variables should be passed by reference” on the line containing “$last = end(array_keys($path));”.

      If you could please shed some light on these issues, I’d be very grateful.

      Many thanks!


    • Anna Foxin
      Posted on

      Anna Foxin Anna Foxin

      Reply Author

      Hi Nedra,
      Sorry for the inaccuracy. The make_title_string is my private function. It changes the first letter in every title’s word to the uppercase. So you can absolutely ignore it.
      Regard to you second note. This line of code was taken from the original code of the author of this blog.


    • priti
      Posted on

      priti priti

      Reply Author

      i’m having issue for multilevel.please help


  • Dev Guy
    Posted on

    Dev Guy Dev Guy

    Reply Author

    Oh this is a really good tutorial, it’s just what I was looking for.


  • FotoAdmin
    Posted on

    FotoAdmin FotoAdmin

    Reply Author

    May be need add microformat or RDF to breadcrums for beautiful view in Google =).


  • Deepak Raikwar
    Posted on

    Deepak Raikwar Deepak Raikwar

    Reply Author

    Hi All,
    Thanks for your post and reply also.
    This is very usefull script.

    I am learner, so can anyone help me out to learn jQuery and PHP.

    Regards,
    Deepak Raikwar


  • hrvi
    Posted on

    hrvi hrvi

    Reply Author

    Your snippet didn’t worked for me. Breadcrumbs names are echoed right, but links to crumbs lower in the tree are all wrong and only works for single directory depth. So I made my version, check it out at http://codepad.org/McSUUNnA . I had some issues with $base_url, but I find this version the most compatible and it works on my local server and on a production server too, although codepad doesn’t get it right.


    • hem
      Posted on

      hem hem

      Reply Author

      thanks hrvi your code works like a charm. I tried your code after i faced the same problem as you. thank you again.


    • Luis
      Posted on

      Luis Luis

      Reply Author

      Many thanks, just what I was looking for, thanks for sharing!


    • Luis
      Posted on

      Luis Luis

      Reply Author

      Many thanks, just what I was looking for, thanks for sharing!


    • @ThisBoyPerforms
      Posted on

      @ThisBoyPerforms @ThisBoyPerforms

      Reply Author

      Thanks man! Works like a charm.


  • Ryan
    Posted on

    Ryan Ryan

    Reply Author

    Thanks Ashley, This is some nice piece of code to implement breadcrumbs.


    • ra
      Posted on

      ra ra

      Reply Author

      okay


  • nicksp
    Posted on

    nicksp nicksp

    Reply Author

    Ah, html in the comments are not working ;(

    So, in order to obtain working code check this http://cdpst.net/pfv1v9yp6 (it’s a code snippets share service)

    Have a nice day.


  • nicksp
    Posted on

    nicksp nicksp

    Reply Author

    Nice tip. Thanks. Thought there is an error in your code on line 12.

    Replace that line by the following piece of code:
    $breadcrumbs[] = ‘‘ . $title . ‘‘;


  • yara
    Posted on

    yara yara

    Reply Author

    Line 12 :

    Replace by :
    $breadcrumbs[] = “$title“;

    Because no replacing varible with single quote 😉


  • DaveBowman
    Posted on

    DaveBowman DaveBowman

    Reply Author

    What’s the use of this bit? If a user has fully dynamic site with clean URLs it is most certainly operated by some sort of a CMS, that surely can do breadcrumbs. And if he hasn’t, this snippet won’t help anyway.


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Dave I think it’s pretty bad of you to assume that every site with clean URL’s uses a CMS system. The point of my tutorials are as much to show the techniques in which to do things as well as being able to use them in web projects.


    • Vitaly Van Deusen
      Posted on

      Vitaly Van Deusen Vitaly Van Deusen

      Reply Author

      My site does not use a CMS. I hard code all my pages, because I don’t want the extra stuff the a CMS can sometimes put in. I have include files for header, footer, and navigation so I only have to edit them once, and the work globally across my site. Don’t assume things until you get to know the website.