Getting the current URL with php

There was a problem with one of the script I’d posted (I think we actually found a different way altogether of doing it) but it was an issue with $PHP_SELF when used in a file that gets included - it ends up showing the name of the INCLUDED file (not the current url).

Just for my future reference, I just tried this instead of PHP_SELF and it seemed to work ok with includes.

“http://”.$_SERVER['HTTP_HOST'].$_SERVER['PATH_INFO']

Alternatively - if there’s a “query string” at the end of the current url that you want to grab as well (ie http://www.domain.com/test.php?variable=value) you can add this onto the end of the line above:

.$_SERVER['QUERY_STRING']

(side note the . is just used to concatenate the different parts)

7 Responses to “Getting the current URL with php”

  1. lynda Says:

    That’s really odd. I have no idea why it would do that. I have php_self in several included files and they all work just fine.

    Odd! :)

  2. Jennifer Says:

    Yeah, when I just tested it now - PHP_SELF worked just fine when in an include. Maybe it was an isolated incident due to a weird setting on that server (?)… don’t know…

  3. lynda Says:

    That’s okay, I didn’t know about the query_string variable and now I do, so it’s all good. :)

  4. Chris Says:

    I’m not sure exactly what the difference is, but I’m using “$_SERVER['REQUEST_URI']” in some of my scripts and it also seems to work well!

    Chris

  5. Jester Says:

    Yeah $_SERVER['REQUEST_URI'] gets everything after the actual host, this bit:

    http://www.host.com/script.php?foo=bar

    So any easy way to get the full, current URL is:

    echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

    Useful for when you want to send emails out and you need to link to the absolute URL.

  6. echo Says:

    This link explains exactly what you mention with some interesting examples. Stuff I hadn’t seen before.

  7. echo Says:

    ooops…my bad…here it is…
    link