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.

0

2 Answers 2

23

How about this?

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

echo getAddress();
3
  • 1
    Conditional statement in $protocol should be isset($_SERVER['HTTPS']) === true. Commented Aug 7, 2014 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
    Commented Mar 23, 2016 at 7:23
  • In case of AJAX request the REQUEST_URI can be different from the REQUEST_URI in address bar. Commented Sep 24, 2019 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.

3
  • Is this code working correctly? Commented Jun 28, 2012 at 13:53
  • Ouput od your code i s localhost/site/tmp/? Commented Jun 28, 2012 at 13:59
  • I suppose, it must work correctly, although I haven't tried it yet. Output will be: localhost/site/tmp/?get1=val1&get2=val2. $str must be get from one of the main function with $_SERVER. And all GET parameters will be added.
    – dpitkevics
    Commented Jun 28, 2012 at 14:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.