PHP: How to get referrer URL?

PHP: How to get referrer URL?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP: How to get referrer URL?

You are encountering a classic web development scenario where $_SERVER['HTTP_REFERER'] returns an empty string. Based on the server variable dump you provided, your environment is standard Apache running CGI/1.1, and the HTTP headers look completely normal. The fact that HTTP_HOST and HTTP_USER_AGENT are populated confirms that the client sent a valid request. So, why is the referrer missing?

The answer lies in how browsers handle security and privacy settings, which is why relying on this variable for analytics is often considered fragile. When a user clicks a link from an email client (like Outlook or Apple Mail) or uses a bookmarklet to send data, the browser frequently omits the Referer header entirely. Even if your site has been visited via a search engine like Google or a social media post, modern privacy-focused browsers and extensions often strip this header by default.

If you need to track where traffic originates in a production environment where HTTP_REFERER is unreliable, you must implement client-side tracking that survives browser quirks. The most robust solution involves injecting a specific HTTP header into the user agent string itself. This requires modifying your JavaScript to append a custom parameter to every outbound link on your site.

Here is how you can implement this without breaking your existing functionality:

  1. Inject a Custom Header: Create a small JavaScript snippet that appends &ref= followed by the current page's URL to the href attribute of all <a> tags on your page.

    document.addEventListener('DOMContentLoaded', function() {
        var links = document.querySelectorAll('a');
        links.forEach(function(link) {
            // Only append if the href doesn't already contain 'ref='
            if (link.href.indexOf('ref=') === -1) {
                link.setAttribute('href', link.href + '&ref=' + encodeURIComponent(window.location.href));
            }
        });
    });
    
  2. Capture the Header in PHP: On your index.php endpoint, read this custom parameter from the query string instead of the server variable. Since it is part of the URL path now, it will persist regardless of whether the browser sends the standard HTTP_REFERER.

    $referrer = isset($_GET['ref']) ? $_GET['ref'] : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Direct');
    
    // Log or store $referrer in your database
    echo "Visitor came from: " . htmlspecialchars($referrer);
    

The Trade-offs You Must Consider

While the JavaScript injection method solves the empty HTTP_REFERER problem, it introduces new variables. First, you are increasing the size of every outgoing link. If a user is bandwidth-constrained or has an older mobile device, appending long URLs to links can degrade performance slightly. However, the impact is usually negligible for modern connections.

Second, this method breaks iframes. If your index.php page is embedded inside an iframe on another site, the JavaScript will modify the parent page's links rather than the frame's content, or it might not execute at all depending on the origin policy. You must ensure this script only runs in top-level windows or use specific selectors to avoid modifying nested frames.

Finally, do not assume that $_SERVER['HTTP_REFERER'] is useless. If the browser sends it (which happens with direct navigation, some search engines, and non-privacy-tightened browsers), you should fall back to it. Always check for the presence of the custom parameter first; if it exists, use it. If not, gracefully degrade to HTTP_REFERER.

For developers working within the Laravel ecosystem, this logic can be encapsulated in a middleware or a helper service that checks the incoming request's query parameters before falling back to server variables. This ensures consistent data collection regardless of the user agent behavior.

Our network