开发者

How to retrieve the URL of a page using PHP?

Newbie question here, is there any inbuilt PHP tag that can be us开发者_如何学Goed to retrieve the URL of a page and echo it on the screen?

Thanks.


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;


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜