Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Breadcrumbs for PHP Lovers

Rated 4.26 (Ratings: 8) (Add your rating)

Log in to add a comment
(30 comments so far)

Want more?

 
Picture of jstetser

Member info | Full bio

User since: December 15, 2000

Last login: December 15, 2000

Articles written: 1

Martin and Adrian started breadcrumb mania, and I'm continuing the tradition with "Breadcrumbs for PHP Lovers." If you want to know why breadcrumbs make good business, read Martin's Breadcrumbs for All. If you need an ASP-based breadcrumb trail generator, Adrian's Breadcrumbs for Those Using ASP should help.

With no further ado, here's how to build a breadcrumb trail in PHP. I wrote the code mostly by porting Adrian's concept to PHP, using native functions whenever possible.

If you're integrating this generator with a homebrew content management system or have a setup where the home page of your site is not accessible via a single "/" absolute URL, you can set $root_url to a different location; the script will automatically modify all paths to suit. Like Adrian's solution, if $page_title is not set, the script will print "Current Page" for the page the user is on.

Save the code below as breadcrumb.php in your includes directory.

<?php

##############################################################################
# breadcrumb.php                  Version 1.1                                #
# Copyright 2000 Jacob Stetser    jstetser@icongarden.com                    #
# Created Dec 30, 2000            Last Modified May 2, 2001                 #
##############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright [and -left] 2000 Jacob Stetser. All Rights Reserved except as    #
# provided below.                                                            #
#                                                                            #
# breadcrumb.php may be used and modified free of charge by anyone so long   #
# as this copyright notice and the comments above remain intact. By using    #
# this code you agree to indemnify Jacob Stetser from any liability that     #
# might arise from it's use.                                                 #
#                                                                            #
# This script is released under the BSD license.                             #
# The author recognizes this script's indebtedness to evolt.org, Martin      #
# Burns, Adrian Roselli and countless other ideas of its kind. This script   #
# is therefore unencumbered free code.                                       #
##############################################################################

function breadCrumb($PATH_INFO) {
	global $page_title, $root_url;

	// Remove these comments if you like, but only distribute 
	// commented versions.
	
	// Replace all instances of _ with a space
	$PATH_INFO = str_replace("_", " ", $PATH_INFO);
	// split up the path at each slash
	$pathArray = explode("/",$PATH_INFO);
	
	// Initialize variable and add link to home page
	if(!isset($root_url)) { $root_url=""; }
	$breadCrumbHTML = '<a href="'.$root_url.'/" title="Home Page">Home</a> &gt; ';
	
	// initialize newTrail
	$newTrail = $root_url."/";
	
	// starting for loop at 1 to remove root
	for($a=1;$a<count($pathArray)-1;$a++) {
		// capitalize the first letter of each word in the section name
		$crumbDisplayName = ucwords($pathArray[$a]);
		// rebuild the navigation path
		$newTrail .= $pathArray[$a].'/';
		// build the HTML for the breadcrumb trail
		$breadCrumbHTML .= '<a href="'.$newTrail.'">'.$crumbDisplayName.'</a> &gt; ';
	}
	// Add the current page
	if(!isset($page_title)) { $page_title = "Current Page"; }
	$breadCrumbHTML .= '<strong>'.$page_title.'</strong>';
	
	// print the generated HTML
	print($breadCrumbHTML);
	
	// return success (not necessary, but maybe the 
	// user wants to test its success?
	return true;
}

?>

To use breadcrumb.php on your pages, you'll need to first include it and, if you desire, set $page_title:

<?php $page_title = "About Us";
include('/includes/breadcrumb.php'); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

<html lang="en-us">
<head>

<title><?php echo $page_title ?></title>
[...]

To print out the breadcrumb trail, call the function like this:

<?php breadCrumb($SCRIPT_URL); ?>

If you are running a solution where all pages are generated by a single php script that parses $PATH_INFO, you may want to set $root_url to the actual script and parse use $PATH_INFO in place of $SCRIPT_URL.

The code is commented so you can easily see where to add or change HTML. Enjoy!

another function

Submitted by pedrito on January 2, 2001 - 09:33.

This one generates a breadcrumb from the URL (and from the directories). Less elegant it seems, but I thought I'd post it anyway

function coma_print_breadcrumb($depth = 0, $separator = " > ") {
	# generates a breadcrumb from the URL - Peter rules November 2000
	global $coma_breadcrumb; 
		$requested = getenv('REQUEST_URI');
		$crumb = split("/",$requested);
		# if no filename requested filename is index.php3
		if (!strstr ($requested,".php3")) $crumb[sizeof($crumb)-1] = "index.php3";
		# loop through sections
		for ($i = $depth; $i  
  

login or register to post comments

Other missing scripting languages

Submitted by MartinB on January 5, 2001 - 02:04.

It'd be very, very cool if we could complete the set of "Breadcrumbs for..." serverside howtos with

  • Breadcrumbs for ColdFusion
  • Breadcrumbs for JSP

Any takers?

login or register to post comments

Translating the viewable text back into an url

Submitted by andrewpander on January 9, 2001 - 16:36.

I think the underscores need to be put back in before the url is printed. At any rate, replacing the last line of the 'for' loop with this worked for me:

$newTrailUrl = str_replace(" ", "_", $newTrail);
$breadCrumbHTML .= '<a href="'.$newTrailUrl.'">'.$crumbDisplayName.'</a> > ';

login or register to post comments

Going deeper?

Submitted by willem on July 16, 2001 - 07:28.

it works ok for me but only on one level....

home > test

when I make another folder in test it just comes up with this

home > deeper

I would like to see

home > test > deeper

anyone gimme a hand?

Willem

login or register to post comments

Problem with vertical depth

Submitted by bilstein on August 1, 2001 - 12:07.

I'm having the same problem as Willem above. In the breadcrumb trail I am only getting the Home and current page texts. The directory structure in between is not showing when the breadcrumb goes beyond one level. The path info is being read correctly. I've used the ASP version of this script and it works great, but I can't figure out why this is failing. Anyone have any ideas?

login or register to post comments

Problem with vertical depth

Submitted by bilstein on August 1, 2001 - 12:07.

I'm having the same problem as Willem above. In the breadcrumb trail I am only getting the Home and current page texts. The directory structure in between is not showing when the breadcrumb goes beyond one level. The path info is being read correctly. I've used the ASP version of this script and it works great, but I can't figure out why this is failing. Anyone have any ideas?

login or register to post comments

Replace $SCRIPT_URL with $PATH_INFO

Submitted by bilstein on August 1, 2001 - 12:27.

Okay, I replaced $SCRIPT_URL with $PATH_INFO in the call and it works. I didn't reset the $root_url to the actual script though. I'm not sure why I had to do this, I don't believe it's being parsed by a single file as mentioned in the notes above, but it works. p.s. sorry for the double-post, I had a twitchy mouse finger. =)

login or register to post comments

Directory Structure?

Submitted by sstaubin on September 7, 2001 - 22:07.

Can anyone give me an example of how the directory structure should look to get this script to work using breadCrumbs($PATH_INFO). I'm using Apache for win32 as a development server therefore my directory structure looks like this:

C:\Apache\htdocs\index.php   ($page_ title = "Home";)
C:\Apache\htdocs\test\test.php  ($page_ title = "Test";)
C:\Apache\htdocs\test\deeper\deeper.php  ($page_ title = "Deeper";)

index.php links to test\test.php which links to test\deeper\deeper.php

I expect the breadcrumb to show index Home > Test > Deeper with links back to index.php, test\test.php and test\deeper\deeper.php

But it doesn't. I'm getting test\deeper\index.php, test\deeper\index.php\test and test\deeper\index.php\test\deeper

login or register to post comments

breadcrumb.php

Submitted by ODag on February 7, 2002 - 23:12.

On page: http://evolt.org/article/Breadcrumbs_for_PHP_Lovers/17/4455/ I read (middle) line: "To use breadcrumb.php on your pages, you'll need to first include it and, if you desire, set $page_title:" To include WHERE? Tnx in advance, Dag

login or register to post comments

Not displaying depth beyond first level

Submitted by webgraph on February 12, 2003 - 10:37.

I'm having the same problem as Willem and bilstein mentioned.

I have the following directory structure:

/firstFolder/secondFile.php

and when I view the index page in firstFolder, the breadcrumbs work correctly, but when I then view secondFile.php, the breadcrumb is displayed as if that file was the next level up in the directory hierarchy.

I tried switching from $SCRIPT_URL to $PATH_INFO in the call, but that doesn't change the behavior.

Thoughts?

Thanks!

login or register to post comments

Not displaying depth beyond first level

Submitted by Audrey on March 9, 2003 - 13:11.

Ditto WebGraph. All of my pages appear as if they reside directly at the root, so desired breadcrumbs effect does not work. If this has been solved, can you please let me know? Thanks, Audrey

login or register to post comments

IIS

Submitted by alanrenouf on March 19, 2003 - 06:16.

Does anybody know how to get this working on IIS as the variables: $SCRIPT_URL $PATH_INFO dont seem to work. Thanks Alan

login or register to post comments

re: IIS

Submitted by foo bar on May 27, 2003 - 17:44.

PHP_SELF should work in most cases. i just wrote a basic (very similar) function
$page_title = "here";

function crumbs($path,$root='')
{
	global $page_title;
	
	$path = preg_split('%\/%', $path, -1, PREG_SPLIT_NO_EMPTY);
	$trail = $root . '/';


	if (count($path) <= 1) {
		// we're in the site root, no links are needed
		return 'Home';
	}
	else {
		// create home link
		echo "<a href=\"$trail\" title=\"Home Page\">Home</a>\n";
		
		for($i=0; $i<(count($path)-2); $i++) {
			// more links needed to be created
			$trail .= $path[$i] .'/';
			$title = ucwords(str_replace('_', ' ', $path[$i]));
			echo "→ <sa href=\"$trail\" title=\"$title\">$title</a>\n";
		}
		
		// output current page title
		echo "→ $page_title \n";
	}
	return true;
}

crumbs($_SERVER['PHP_SELF']);

login or register to post comments

re: paths

Submitted by foo bar on May 27, 2003 - 17:46.

also, if you're having trouble with the paths/doc_root, do a print_r($_SERVER) and you'll be able to see exactly what vars are being provided by the server.

login or register to post comments

Problem with vertical depth

Submitted by calaca32 on July 8, 2003 - 23:01.

If you are having problems with the vertical depth {index>page, instead of index>folder>page} make sure that "register_globals = On" in your php.ini file. I had the same problem, I turned it on and worked afterward.

login or register to post comments

Turning on register_globals is the wrong solution

Submitted by mis on August 1, 2003 - 17:41.

Setting register_globals to On is slightly overkill to solve this problem, and will have lots of unwanted side effects. It might also be impossible for a lot of people if they can't change config settings themselves.

Better way to fix it would be to use $GLOBALS['PHP_SELF'] or $GLOBALS['PATH_INFO'] (or whatever HTTP server CGI var you're using) when calling the breadcrumbs generation function.

login or register to post comments

I'm in same boat as sstaubin

Submitted by gatman on August 29, 2003 - 17:01.

Guess I do not understand $PATH_INFO. where is this coming from? pathinfo() I understand is a function - where is the value? Also, how would this effect search engines (internal or external of site) that base indexing on titles. Titles are given weight (sometimes alot and some a little) Isn't the title buried in this manner and diluting or eliminating any search function on title?

login or register to post comments

If neither $PATH_INFO nor $SCRIPT_URL work...

Submitted by truesdel on September 3, 2003 - 17:14.

try this:
  breadCrumb($_SERVER[SCRIPT_URL]);

login or register to post comments

includes

Submitted by edonn on September 20, 2003 - 20:58.

the includes used are all relative right? if i have pages deeply nested in different folders, does that mean that each folder requires its own breadcrumb.php file? is it possible to have just one breadcrumb.php file and have all the files (each in a diff folder) pointed at it?

login or register to post comments

includes used are all relative right?

Submitted by truesdel on September 20, 2003 - 21:25.

Hopefully, if you are using PHP for your site, you only have a few templates for your entire site anyway, right?

I have one instance of 'breadcrumb.php' in my root /includes directory and this is what my templates reference. All my more-or-less static web pages are symbolic links to one file -- /master.php -- which pulls in the appropriate template, menus, and content. So if I want to change from using '/includes/breadcrumb.php' to '/bin/brdcrmb.inc' tomorrow, I only need to edit one line in the entire site (well, two if the call to the function changes...)

  --scott

login or register to post comments

Use my breadcrumb class...

Submitted by murlyn on September 23, 2003 - 00:24.

I created a breadcrumb class that so far has won one award and I believe is simple to use...

Breadcrumbs Class

If you need any help please use the email address on the site.. and Ill get back to you asap :)

login or register to post comments

XML markup

Submitted by designcurb on October 22, 2003 - 01:55.

We are building a site which needs to be in the XHTML format. As soon as the page reaches line 3 of the page:

&lt;?xml version="1.0" encoding="iso-8859-1"?&gt;


We get a parsing error. Is there anyway around this. I guess its because the php engine isn't geared upto parsing XHTML yet.

Can anybody suggest a hack around this???

login or register to post comments

Re: XML markup

Submitted by webgraph on October 22, 2003 - 02:27.

Hi there (FYI, this isn't the best place to post this sort of question, but I'll let it slide this time ;-)

Here's what you need to do:

&lt;?php<br />
<br />
echo "&lt;?xml version=\"1.0\" encoding=\"iso-8859-1\"?&gt;";<br />
<br />
?&gt;

This tells PHP to output the line you need, without misinterpreting it as PHP code.

login or register to post comments

Displaying a ' page history' page

Submitted by carnuke on January 20, 2004 - 02:43.

I use a xoops cms and wnat to put this breadcrumb script in the code. What I also want is to be able to link to a separate page showing a visitors "history of pages visited" as a list of breadcrumb links. Is this possible with this script? Many thanks for your help. Richard

login or register to post comments

Re: Displaying a 'page history' page

Submitted by murlyn on January 20, 2004 - 09:35.

The only way that I can see you doing this is using output buffering and capture the breadcrumb data into a variable and then save that variable into a database, in whichever way that you would like. Since it is a history of pages visited, they obviously would have to be logged in, so a combination of their username, and the page visited, you could do this.. it's not something my class will do, since that really has nothing to do with breadcrumbs, but it's interesting none-the-less :)

login or register to post comments

Danger using PATH_INFO

Submitted by cheeseysnacks on October 6, 2004 - 02:09.

Newer versions of Apache need to have AcceptPathInfo set to ON in the configuration file otherwise PATH_INFO is not set. Hence if AcceptPathInfo is OFF page/page.php/morepages will return a 404 This is fine if you have your own server and access to the Config, but many people using shared hosting will have to find alternative ways. This will obviously affect the results of this tutorial.

login or register to post comments

I have a slight problem generating a breadcrumb trail

Submitted by Paithar on December 20, 2005 - 22:35.

I've only been coding with PHP for about 4 months now. I'm working for a company that has this site especially designed for it's clients and everything is written in PHP. No biggy except for one thing. All of their main php scripts are in one folder. After a little tweaking of the breadcrumbs.php script I've got it to somewhat work but my problem is that no matter how far into the site they go, since pretty much everything is in just one folder my breadcrumb trail always display just two links. It always displays the login page link and the link for the page the user is currently on. I know this is probably not a good design for this website but it's what they had when I started and I don't see them changing it any time soon. So, for example, if a user clicks on the following menu links in order... Tools and Utilities (on the main menu) Internal Reports (on the tools and utilities menu) I want the trail to display... Main Menu > Tools and Utilities > Internal Reports. Currently it just displays Main Menu > Internal Reports. Anyone know of a way to display the whole trail info of how the user got to where they are currently at? I've gone 5 deep into the menu system and I still only have the main menu link and then the page they are on. I'd really appreciate any help I can get on this one. Thanks!

login or register to post comments

Fixed missing directory names between home and filename crumbs

Submitted by indigohat on October 17, 2006 - 23:21.

When I used the above code (I tried several other snips as well with the same result), it would print out 'Home > File Name' no matter where it was in the directory structure.

I am including my breadcrumb file from an include of the main file and I suspect that the issue is related to that.

Anyhoo, I changed this snip of code:

// Replace all instances of _ with a space
$PATH_INFO = str_replace("_", " ", $PATH_INFO);
// split up the path at each slash
$pathArray = explode("/",$PATH_INFO);

... to use $_SERVER['REQUEST_URI'] instead of $PATH_INFO and that seemed to do the trick.

So now it looks like :


// Replace all instances of _ with a space
$PATH_INFO = str_replace("_", " ", $_SERVER['REQUEST_URI']);
// split up the path at each slash
$pathArray = explode("/",$PATH_INFO);

login or register to post comments

Great script but going deeper still not working

Submitted by solio on November 20, 2007 - 00:00.

I've been playing around with this script for a while, but still can't figure out how to get the deeper links to work. I did have some success from the mods above, but when then the breadcrumb simply displayed the folders as well (e.g. home > includes > corporate > articles > contact us - which is obviously undesirable

Isn't there an easy fix to just display the actual file names and not their parent directories? e.g. Home > Company Info > Contact Us

Any help greatly appreciated TIA

login or register to post comments

Found a fix!

Submitted by shrprmf on May 9, 2008 - 04:49.

Try the following code for calling the function:
<?php
breadCrumb
($_SERVER['REQUEST_URI']);
?>
This fixed the not displaying 'deeper and deeper' issue I was having and probably most other people. Hope it helps!

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.