tags:

views:

74

answers:

4

Newbie question here, is there any inbuilt PHP tag that can be used to retrieve the URL of a page and echo it on the screen?

Thanks.

+2  A: 

Echos the URL of the current page.

$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} 
else 
{
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
echo $pageURL;
Chacha102
+1 very conscise. @OP: You can see all server variables that are available to you (Port, various URIs, request headers and languages, etc.) Using `print_r($_SERVER);` and viewing the output's source code.
Pekka
It's actually the code that Google uses to find their page url.
Chacha102
Thanks Chacha, this works. I thought there might be some inbuilt tag similar to php_info since this seems like a very standard task but apparently not.
Jackie
If `$_SERVER["HTTPS"] == "on"`, I believe you can use `$_SERVER["SCRIPT_URI"]` and get the whole thing. Or is that just with Apache?
Anthony
Someone on this question: http://stackoverflow.com/questions/717874/serverscripturi-not-working-alternative had problems with it.
Chacha102
A: 

Take a look at the $_Server variable. Specifically you probably want the REQUEST_URI value.

Parrots
A: 
$base_url = _SERVER["HTTP_HOST"];
$url_path = _SERVER["REQUEST_URI"];

echo $base_url.$url_path;

Assuming the requested page was http://sample.org/test.php, you would get:

 sample.org/test.php

You would have to add more $_SERVER variables to get the scheme (http://). REQUEST_URI also leaves any GET variables intact, so if the page request was http://sample.org/test.php?stuff=junk, you would get:

 sample.org/test.php?stuff=junk

If you wanted that left off, use $_SERVER['PHP_SELF'] instead of REQUEST_URI.

If you want a really easy way to see which global variables are available, create a page with the following:

<?php

phpinfo();

?>

and put that script in any directory you are curious about. Not only will you see all sorts of neat info, you will also see how various factors such as HTTP vs HTTPS, mod_rewrite, and even Apache vs IIS can set some global variables differently or not at all.

Anthony
+1  A: 

If your web server runs on standard ports (80 for HTTP or 443 for HTTPS) this would work:

getservbyport($_SERVER['SERVER_PORT'], 'tcp') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
Alix Axel