6

Possible Duplicate:
How to get full URL on the address bar using PHP

I use this function, but it does not work all the time. Can anyone give a hint?

function sofa_get_uri() {
    $host = $_SERVER['SERVER_NAME'];
    $self = $_SERVER["REQUEST_URI"];
    $query = !empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null;
    $ref = !empty($query) ? "http://$host$self?$query" : "http://$host$self";
    return $ref;
}

I want to retrieve the link in address bar (exactly) to use it to refer user back when he sign out. The urls are different:

http://domain.com/sample/address/?arg=bla

http://domain.com/?show=bla&act=bla&view=bla

http://domain.com/nice/permalinks/setup

But I can't get a function that works on all cases and give me the true referrer.

Hint please.

Community
  • 1
  • 1
Ahmed Fouad
  • 2,963
  • 10
  • 30
  • 54

2 Answers2

23

How about this?

function getAddress() {
    $protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

echo getAddress();
Juha Untinen
  • 1,806
  • 1
  • 24
  • 40
  • 1
    Conditional statement in `$protocol` should be `isset($_SERVER['HTTPS']) === true`. – Gungor Budak Aug 07 '14 at 19:09
  • be aware: this is quick and dirty solution, but works most of time. this approach contains couple of things worth of being considered. HTTPS and HTTP_HOST aren't standard and could be omitted or wrongly configured. HTTP_HOST could be empty or contain any string data (+ could be "client-hacked" using Host in request header). best practice is to use multiple checks (SERVER_PROTOCOL and REQUEST_SCHEME along with HTTPS; SERVER_NAME is more reliable than HTTP_HOST but also could be wrongly configured). Bottom of line, this function works most of time but it's not universal and reliable solution. – Wh1T3h4Ck5 Mar 23 '16 at 07:23
  • In case of AJAX request the REQUEST_URI can be different from the REQUEST_URI in address bar. – Vikas Khunteta Sep 24 '19 at 11:12
-2

You could use functions above to retrieve URL till GET parameters. So You have string like = 'localhost/site/tmp' (example). After that you could just loop through GET parameters if can't get anything else to work. Add '?' at the end of string manually.

$str = 'localhost/site/tmp/?'
foreach ($_GET as $key => $value) {
    $str .= $key.'='.$value.'&';
}
substr_replace($str, "", -1);

echo $str; At the end You are deleting last symbol which is '&' and is not needed.

Suresh kumar
  • 2,002
  • 1
  • 19
  • 28
dpitkevics
  • 1,238
  • 8
  • 12