I am trying to override Yoast breadcrumbs using the PHP $_SERVER['HTTP_REFERER']but am getting an index error

49 views Asked by At

I am getting an undefined array error. The goal here is to override the second link to simply go back one page. An example is

Custom Templates > Category > Template

I added the following code to hijack the breadcrumb structure. Yoast kept adding /blog into the url, and this is a custom post type. My hack is working, however I am getting an error on the server:

PHP Warning: Undefined array key "HTTP_REFERER"

add_filter('wpseo_breadcrumb_links', 'wpse_332125_breadcrumbs');
function wpse_332125_breadcrumbs($links) {
    if(is_singular('custom-template')) {
        $links[2] = array(
            'text' => 'Category',
            'url' => $_SERVER['HTTP_REFERER'],
            'allow_html' => 2
        );
    }
    return $links;
}
1

There are 1 answers

0
Álvaro González On

The Referer HTTP request header is supplied by browser. It's trivial to forge, but it can also point to a third-party web site that links to yours. Some tools (browser extensions, firewalls...) strip it altogether for security/privacy reasons. And you can't always trust on intermediate proxies to pass on the header.

Said that... If you want to use it, you need to cover several cases:

  • Header is missing entirely
  • Value does not contain a properly formatted full absolute URL
  • URL belongs to an external site
  • User does not actually come from that URL

These points aren't hard to deal with from a technical standpoint (you have isset(), parse_url(), str_starts_with()...), but some of them they require making some decisions regarding functionality and security.

Possible alternatives to replace or complement this:

  • Keep track of visited pages yourself in server-side storage (session, database...). This is reliable and flexible, but may not play nice with multi-tab browsing.
  • Make it a client-side feature and implement it with JavaScript, using data from browser history (e.g. tabs.goBack()).
  • Do nothing, and educate users to use browser's Back button. In my experience, this is something that most users are typically familiar with.