3.7. Creating Breadcrumb Links

Problem

You need to help users navigate your site by putting a chain of links, or breadcrumb, that matches your site structure.

Solution

Use a PHP script to generate the links on-the-fly from the directory names on your web site (see Figure 3-8).

Discussion

Breadcrumb links make a nifty addition to your site's navigation. Although they shouldn't replace a site's primary or secondary navigation, they give visitors an additional tool to use when browsing a deep site.

Breadcrumb navigation shows a trail of links that mirrors a site's structure

Figure 3-8. Breadcrumb navigation shows a trail of links that mirrors a site's structure

Using the names of your web site directories, this PHP script creates links to the main pages in every directory above the current page.

	<?
	$full_path = substr(getenv("REQUEST_URI"),1);
	$full_path = trim($full_path,"\/");
	$bc = split("\/", $full_path);

First, the script defines the variable $full_path as the names of the directories and the file that are part of the current page's URL (leaving out the http:// and the domain name) and trims the leading and trailing slashes from the string.

Using the split() function, the script turns the string value of $full_path (products/industrial/widgets/a111.php) into a four-value array—three directory names and a filename.

Next, the script will take a closer look at the filename (or lack thereof) of the URL that has been requested.

	if (strstr(end($bc), "index")) { $j=2; } ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.