Bread-crumb script using PHP

To create a bread-crumbs script we firstly need to get the current URL. We do this by using the $_SERVER super-global variable in PHP.

if($location = substr(dirname($_SERVER['PHP_SELF']), 1)) 
   $dirlist = explode('/', $location);
   $dirlist = array();

We need to split the name up so that we can link to all the separate directories that the current document is in. The dirname function returns the directory of the script and we then remove the trailing forward-slash and split the string up to get all the directories. If the location string is empty then we return an empty array as there are no directories to list.

$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo '<a href="'.$address.'">Home</a>';

Now that we have an array of the directories we push the name of the file onto the stack. The first link created is a link to the root directory. We will now add links to the other directories. When array_push is called it returns the new number of elements in the array so we will store this value and use it it iterate through the array later.

for($i = 0; $i < $count; $i++)
   echo '&nbsp;&raquo;&nbsp;<a href="'.($address .= '/'.$dirlist[$i]).'">'.$dirlist[$i].'</a>';

The links are output and separated by double arrows (ยป).

NB: When a variable is assigned a new value, that value is returned, therefore in this code when the address variable is updated the new value will be returned and to the string.




No tags