Home : Webmonkey : Code : Breadcrumbs : History Crumbs : Php


It's much nicer to do some things at the server side. When you do your processing on the server, you can just send HTML to the browser. This means that you don't have to worry quite so much about browser differences with regards to JavaScript.

The following code demonstrates history breadcrumbs, implemented in PHP. You may also want to check out position breadcrumbs


The example opens in a new window.


To preserve maintainability, I recommend that you try to segregate content from code. What I tend to do is have one or more 'functions' php files, which get included at the top of pages. I put as much code as is sensible into functions and then call the functions where they're needed in the page. If a function needs to be changed, I change it on one place only. It also makes maintaining content easier, if you're not constantly tip-toeing around chunks of code.

Drop the code into a file called functions.php. Be sure to include the functions.php file in each page as shown below. It must be at the top of the page, otherwise PHP will warn you that it can't set the cookie

$pageName = 'page 1';
include ($_SERVER['DOCUMENT_ROOT']  . '/includes/functions.php'); ?>

    <title><?php echo $pageName; ?></title>
<p><?php breadcrumbs(); ?></p>



The contents of functions.php file follows:

Copyright Justin Whitford 2006.
Perpetual, non-exclusive license to use this code is granted
on the condition that this notice is left in tact.
$staleCrumbList = explode('|',$_COOKIE['breadcrumbs']);
if ( 
      $_SERVER['PHP_SELF'].'!'.$pageName !=
  $startPoint=(count($staleCrumbList) < $trailLength+1)?0:1;

function breadcrumbs(){
  $crumbList = explode('|',$_COOKIE['breadcrumbs']);
  $returnString = '';
    $crumb=explode('!', $crumbList[$i]);
    $returnString .= "<span id='bc$i' class='crumb'>"
      ."<a href='$crumb[0]'>$crumb[1]</a> | </span>";
  $crumb=explode('!', $crumbList[count($crumbList)-1]);
  echo $returnString.$crumb[1];



This code was written when I was still fairly new to PHP, so it's probably not quite as elegant as it could be.

When the page is loaded, the server immediately updates the breadcrumb trail that is stored in a cookie. This is why the include must be at the top of the page. When a server sets a cookie, it does it using an HTTP header. If the server has already begun sending the page, it can no longer modify the header.

Once the breadcrumb trail is stored in the cookie, it's just a matter of retrieving and formatting it, using the breadcrumbs() function.