Get original URL referer with PHP?
Asked Answered
D

4

111

I am using $_SERVER['HTTP_REFERER']; to get the referer Url. It works as expected until the user clicks another page and the referer changes to the last page.

How do I store the original referring Url?

Dania answered 8/12, 2009 at 4:27 Comment(0)
E
139

Store it either in a cookie (if it's acceptable for your situation), or in a session variable.

session_start();

if ( !isset( $_SESSION["origURL"] ) )
    $_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];
Exigible answered 8/12, 2009 at 4:28 Comment(2)
Please note @pcp 's advice in the answer below!Marybethmaryellen
Note that you should also check if http_referer exists, as it often doesn't, which could cause an "Undefined index" error.Prejudge
P
18

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

Pyrophotometer answered 8/12, 2009 at 4:30 Comment(0)
T
4

Store it in a cookie that only lasts for the current browsing session

Temporal answered 8/12, 2009 at 4:29 Comment(0)
P
4

Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.

Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):

if(!isset($_COOKIE['origin_ref']))
{
    setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}

Then you can access it later:

$var = $_COOKIE['origin_ref'];

And to addition to what @pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.

Projector answered 8/1, 2017 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.