How to make pHP bread crumbs

Learn how to make breadcrumbs with a simple PHP example that helps you keep track of user navigation.

Making PHP Breadcrumbs

Breadcrumbs are a great way to help your website visitors easily navigate through your site. They are also a great way to improve your website’s SEO since they help search engines better index your website’s content. Fortunately, it’s easy to create breadcrumbs for your website using PHP.

To get started, you’ll need to define a few variables. The first is a string that defines the “home” page. This is the page that will be the starting point of the breadcrumb trail. For example:

$home_page = "Home";

The next variable is an array that contains the names of all of the pages on your website. For example:

$pages = array(
    "Home" => "index.php",
    "About" => "about.php",
    "Contact" => "contact.php",
    "Blog" => "blog.php"
);

Next, you’ll need to define a variable that contains the current page. You can do this by using the $_SERVER['PHP_SELF'] variable. This variable contains the URL of the current page. For example:

$current_page = $_SERVER['PHP_SELF'];

Once you have all of these variables defined, you can start creating the breadcrumb trail. To do this, you’ll need to loop through the $pages array and compare the $current_page variable to each page’s URL. If the URLs match, then the page is added to the breadcrumb trail. For example:

$breadcrumb = "";

foreach ($pages as $name => $url) {
    if ($url == $current_page) {
        if ($breadcrumb == "") {
            $breadcrumb = $name;
        } else {
            $breadcrumb .= " » " . $name;
        }
    }
}

$breadcrumb = $home_page . " » " . $breadcrumb;

Finally, you can output the breadcrumb trail using the $breadcrumb variable. For example:

echo $breadcrumb;

That’s all there is to it! With a few simple lines of PHP code, you can easily create breadcrumbs for your website and improve your website’s SEO.

Answers (0)