php 获取当前网址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5216172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting current URL
提问by I-M-JM
I am using following code to get the current URL
我正在使用以下代码获取当前 URL
$current_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
Is there any other way to get the same, or may be better way to get current URL?
有没有其他方法可以获得相同的结果,或者可能是获取当前 URL 的更好方法?
Thanks.
谢谢。
回答by diEcho
From the reference:
从参考:
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
回答by Jacob
You have to be careful relying on server variables, and it depends what the webserver wants to give you... Here's a fairly failsafe way to get the URL.
你必须小心依赖服务器变量,这取决于网络服务器想要给你什么......这是一个相当安全的获取 URL 的方法。
$url = '';
if (isset($_SERVER['HTTPS']) && filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN))
$url .= 'https';
else
$url .= 'http';
$url .= '://';
if (isset($_SERVER['HTTP_HOST']))
$url .= $_SERVER['HTTP_HOST'];
elseif (isset($_SERVER['SERVER_NAME']))
$url .= $_SERVER['SERVER_NAME'];
else
trigger_error ('Could not get URL from $_SERVER vars');
if ($_SERVER['SERVER_PORT'] != '80')
$url .= ':'.$_SERVER["SERVER_PORT"];
if (isset($_SERVER['REQUEST_URI']))
$url .= $_SERVER['REQUEST_URI'];
elseif (isset($_SERVER['PHP_SELF']))
$url .= $_SERVER['PHP_SELF'];
elseif (isset($_SERVER['REDIRECT_URL']))
$url .= $_SERVER['REDIRECT_URL'];
else
trigger_error ('Could not get URL from $_SERVER vars');
echo $url;