Alternative for $_SERVER['HTTP_REFERER'] PHP variable in MSIE

孤街浪徒 提交于 2019-11-27 22:13:44

If you only need to use the referrer information internally for your website (ie: between pages of your website, not externally), you can manually keep track of a user's referrer information.

// Get the full URL of the current page
function current_page_url(){
    $page_url   = 'http';
    if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'){
        $page_url .= 's';
    }
    return $page_url.'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}

/* (Assuming session already started) */
if(isset($_SESSION['referrer'])){
    // Get existing referrer
    $referrer   = $_SESSION['referrer'];

} elseif(isset($_SERVER['HTTP_REFERER'])){
    // Use given referrer
    $referrer   = $_SERVER['HTTP_REFERER'];

} else {
    // No referrer
}

// Save current page as next page's referrer
$_SESSION['referrer']   = current_page_url();

Then, to access the referrer, just use the $referrer variable.

if(isset($referrer)){
    echo 'Referred from "'.$referrer.'"';
    echo '<a href="'.$referrer.'">Back</a>';
} else {
    echo 'No referrer';
}

That way, if a user visits http://www.example.com/page_1.php, they will see the referrer information if their browser has provided it, otherwise no referrer. Then when they visit http://www.example.com/page_2.php, and any subsequent pages of your site, the referrer will be accessible.

Please don't use session to guess the referrer. This will lead to undesired behaviour and strange errors.

If you really need to know the referring page, pass it via request parameter. You can add the parameter with JS script or on the server side.

jQuery variant for all links on the page:

$(document).ready(function(){
    $('a').on('click', function(e) {
        url = this.getAttribute('href');
        // Check if the page is internal.
        if (url.charAt(0) != '/') {
            return;
        }
        e.preventDefault();
        // Append referrer.
        url += url.indexOf('?') === -1 ? '?' : '&';
        url += 'referer=' + encodeURIComponent(document.URL);
        window.location = url;
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!