Sat. Mar 28th, 2020


Codes for Coders

Display breadcrumbs on your site using PHP

1 min read
php breadcrumb

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.


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 = ' &raquo; ', $home = 'Home') {
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = Array("<a href=\"$base\">$home</a>");
$last = end(array_keys($path));
foreach ($path AS $x => $crumb) {
$title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));
if ($x != $last)
$breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
$breadcrumbs[] = $title;
$base .= $crumb . '/';
return implode($separator, $breadcrumbs);

Display Breadcrumb:

You are here: <?= breadcrumbs(' ♥ '); die; ?>


Download Source code

Leave a Reply

Your email address will not be published. Required fields are marked *