For a redesign project at work, the new design called for bread crumbs. In my opinion, bread crumbs are a great thing to add to a site, and others agree. I didn’t want to have to specify anything on each page for the bread crumbs to work, so I wanted to do it all dynamically.

For the project at work, I did it in ColdFusion; but on my own, I did it in PHP. I figured the way that I would have to do it would be to parse the URL to see which folders I was in.

The Code

File: breadcrumbs.php

<?php require('buildbreadcrumbs.php'); ?>

<ol id="breadCrumbs">
 <li class="first"><a href="/">Home</a></li>
<?php
 $breadCrumbs = $_SERVER['REQUEST_URI'];
 if($breadCrumbs != '') {
  $crumbUrl = '/';
  $toks = split('/', $breadCrumbs);
  for($i = 1; $i < count($toks) - 1; $i++) {
   $crumbUrl .= $toks[$i] . '/';
   if($breadCrumbMapping[$toks[$i]] != NULL) {
    echo '<li><a href="'.$crumbUrl.'">'.$breadCrumbMapping[$toks[$i]].'</a></li>';
   } else {
    echo '<li><a href="'.$crumbUrl.'">'.$toks[$i].'</a></li>';
   }
  }
  echo '<li class="last">'.$pageTitle.'</li>';
 }
?>
</ol> 

The Explanation

The first thing that I do, is include the file buildbreadcrumbs.php (I’ll get to that later). Then the idea is that we will determine what folders we are in, based on the URL. We split the URL based on the slashes and step through them to make links.

Now, back to the File: buildbreadcrumbs.php

<?php
$breadCrumbMapping = Array();

/*Folders to be mapped*/
$breadCrumbMapping['f1'] = "Folder 1";
$breadCrumbMapping['f2'] = "Folder 2";
$breadCrumbMapping['f3'] = "Folder 3";
?> 

This file is building as associative array to display different text than the folder name. There are some situations where the folders are not too pretty, so basically you just add the folder name (f1, f2, f3) to the associative array and assign it a “pretty” name (Folder 1, Folder 2, Folder 3). If you don’t assign a pretty name to a folder, it will just display the folder name instead.

I made an example page to see the bread crumbs in action.

You can download the scripts here: