15 August 2013

PHP Get Referrer Url

in Php $_SERVER array consists of various data in it. Such as;
  • SERVER_NAME
  • REQUEST_METHOD
  • QUERY_STRING
  • HTTP_REFERER
Where the  HTTP_REFERER is the page address which the user agent referred.
Note that it is not guaranteed that this referrer set.
If the visitor comes from the bookmark, it will not be set.

So if it is set, we can get the url of the referrer by ;

$url="";
if(isset($_SERVER["HTTP_REFERER"]))
    $url = $_SERVER["HTTP_REFERER"];


Why we need this referrer url ?
Well I use this referrer url to redirect user to a certain page after a certain job done.
For example, log in user, than redirect to user to his/her profile page.

Example;

$url="";
if(isset($_SERVER["HTTP_REFERER"]))
    $url = $_SERVER["HTTP_REFERER"];

// ... do some job here ...

Header("Location: ".$url);
exit();

This may helpful when a user tries to access a log in required content, after log in successful he/she will be redirected to the previous page and continue whatever he/she will do on that page.

Note that, it is not always a good idea to trust this referrer url, referrer url should be stored in SESSION or cookie will be more secure.

2 comments:

Recep Altun said...

Merhabalar.

İnternette tesadüfen karşılaştığım ve çok beğendiğim "bilgiemlak.com.tr" sitesinin mimarı olmanız hasebiyle blog sayfanızı ziyaret etmiş bulunuyorum.

Çalışmalarınızda başarılar dilerim.
Selam ve dualarımla birlikte en Güzel'e emanet olun.

alper said...

Çok teşekkür ederim Recep Bey,
faydalı olabildiyse ne mutlu bize.

Güzel günler dilerim.