1

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
  • Which page? The current one (i.e., the one being generated by the PHP script itself)? Commented Jan 17, 2010 at 22:53
  • This is very similar to: stackoverflow.com/questions/2079457/… . And look, I used the same function to answer it! Commented Jan 17, 2010 at 22:54

4 Answers 4

2

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;
Sign up to request clarification or add additional context in comments.

5 Comments

+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.
It's actually the code that Google uses to find their page url.
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.
If $_SERVER["HTTPS"] == "on", I believe you can use $_SERVER["SCRIPT_URI"] and get the whole thing. Or is that just with Apache?
Someone on this question: stackoverflow.com/questions/717874/… had problems with it.
1

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']

Comments

0

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

Comments

0
$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.