How to get the http referer in laravel?

Viewed 54383

I'm trying to get the Referer of my users. Like if they come from facebook, youtube, google or anything else.

Now I've tried something like that:

$referrer = $this->request->headers->get('referer');
$url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession();
return $url ?: $this->to('/'); // returns: Method referer does not exist.

This:

return $_SERVER["HTTP_REFERER"] // returns Undefined index: HTTP_REFERER

that:

session_start();
    
if ( !isset( $_SESSION["origURL"] ) ) {
    $_SESSION["origURL"] = $_SERVER["HTTP_REFERER"]; // returns Undefined index: HTTP_REFERER
}

But nothing worked like expected.

Does someone know a solution how I can check the referer?

I need that because I want to check if the user comes from some specific URL's and if so, I want to give the user some extra "clicks" to rank up. Something like a small affiliate system.

8 Answers

Laravel way of getting referer:

request()->headers->get('referer');

You can use the request() helper:

request()->headers->get('referer');

or the Request facade:

Request::header('referer');
Request::server('HTTP_REFERER'); // same thing as above

I hope this message finds you happy with your code. However, if you are facing any issue with referrer URL, you probably should read this article https://scotthelme.co.uk/a-new-security-header-referrer-policy/.

The Referrer Policy header is the key behind such an issue. I have been facing problem with referrer URL in my Laravel + NGINX application and tried all possible ways to fix that by code mentioned in above comments (back, previous, header etc.) but finally found this article to enrich my knowledge before fixing my issue appropriately.

It's up to the client to send the referrer information int he HTTP request's header.

So if the client (browser, app, etc.) doesn't send the referrer, it won't be available to the server in the request headers. I guess the WhatsApp app has disabled sending the referrer, so there is no way to get it.

In some browsers, sending of the referrer information can be turned off in the settings or with a extension. It is also easily spoofed with curl for instance, so it cannot be relied on as a security measure.

More info in my answer here: https://stackoverflow.com/questions/49050268/does-document-referrer-equal-the-http-referer-header/49050494

If your unsure about the client sending the referrer, it's easy to check it with JavaScript (referrer is spelled here differently from the HTTP header, to add to the confusion):

console.log(
    document.referrer
);
Route::get('/send', function (Request $request) { 
    echo $request->headers->get('referer');
});

In addition to RJH answer we can use url() helper

url()->previous();

If you want to go back to the page that initialise the request, we simply write this (usually in the controller):

return redirect()->back();
Related