如何实现获取来源URL并在当前页面URL添加referrer参数
Can we modify the address bar URL to include the referrer when coming from an external link?
Hey Manoj, great question! This is absolutely doable—here's a straightforward way to implement what you're asking for, with some key details to avoid common pitfalls:
How it works
The core idea is to check if we have a valid referrer and the current URL doesn't already have the referrer parameter (to prevent infinite redirect loops). If both conditions are met, we'll redirect the user to the same page but with the referrer added as a query parameter.
Modified PHP Code
<?php // Check if we have a referrer AND the current URL doesn't already include the referrer parameter if (isset($_SERVER['HTTP_REFERER']) && !isset($_GET['referrer'])) { // Encode the referrer URL to safely handle special characters like & or ? $encoded_referrer = urlencode($_SERVER['HTTP_REFERER']); // Build the new URL with the referrer parameter $new_url = $_SERVER['PHP_SELF'] . '?referrer=' . $encoded_referrer; // Send a temporary redirect header (302 is ideal here since referrers are per-visit) header("Location: " . $new_url, true, 302); exit; // Stop script execution immediately after redirect to avoid extra output } else { // Either no referrer exists, or we're already on the URL with the parameter $ref_url = isset($_GET['referrer']) ? urldecode($_GET['referrer']) : 'No referrer set'; } ?>
Key Notes to Keep in Mind
- Avoid infinite loops: The check for
!isset($_GET['referrer'])is critical. Without it, after redirecting to the URL with the parameter, the page would detect the previous URL as the referrer and redirect again, creating an endless loop. - URL encoding: Using
urlencode()ensures that special characters in the referrer URL (like&,?, or spaces) don't break the structure of your new URL. We useurldecode()later to get back the original referrer string. - Redirect type: A 302 temporary redirect is the right choice here because referrers are specific to each visit—you don't want browsers to cache this redirect permanently.
- Referrer limitations: Keep in mind that
$_SERVER['HTTP_REFERER']isn't always available. It won't be sent if:- The user types the URL directly into the address bar
- The user comes from an HTTPS site to an HTTP site (some browsers block this for security)
- The user's browser is configured to not send referrers
- The link was opened from a local file (like
file:///)
In all those cases, the address bar will stay as the original URL, which is expected behavior.
内容的提问来源于stack exchange,提问作者Manoj Soni
相关产品推荐
相关产品推荐

