我使用这段代码来获得完整的URL:
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
问题是我在我的.htaccess中使用了一些掩码,所以我们在URL中看到的并不总是文件的真实路径。
我需要的是得到URL, URL中写了什么,不多不少——完整的URL。
我需要得到它如何出现在web浏览器的导航栏,而不是服务器上文件的真实路径。
我使用这段代码来获得完整的URL:
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
问题是我在我的.htaccess中使用了一些掩码,所以我们在URL中看到的并不总是文件的真实路径。
我需要的是得到URL, URL中写了什么,不多不少——完整的URL。
我需要得到它如何出现在web浏览器的导航栏,而不是服务器上文件的真实路径。
当前回答
我使用了下面的代码,它对我来说工作得很好,对于HTTP和HTTPS这两种情况。
function curPageURL() {
if(isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] != 'on' )) {
$url = 'https://'.$_SERVER["SERVER_NAME"];//https url
} else {
$url = 'http://'.$_SERVER["SERVER_NAME"];//http url
}
if(( $_SERVER["SERVER_PORT"] != 80 )) {
$url .= $_SERVER["SERVER_PORT"];
}
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
echo curPageURL();
Demo
其他回答
$page_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
更多信息:如何使用PHP获取页面的完整URL
我使用了下面的代码,它对我来说工作得很好,对于HTTP和HTTPS这两种情况。
function curPageURL() {
if(isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] != 'on' )) {
$url = 'https://'.$_SERVER["SERVER_NAME"];//https url
} else {
$url = 'http://'.$_SERVER["SERVER_NAME"];//http url
}
if(( $_SERVER["SERVER_PORT"] != 80 )) {
$url .= $_SERVER["SERVER_PORT"];
}
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
echo curPageURL();
Demo
HTTP_HOST和REQUEST_URI必须加引号,否则会在PHP 7.2中抛出错误
使用:
$actual_link = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
如果你想同时支持HTTP和HTTPS:
$actual_link = (isset($_SERVER['HTTPS']) ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
这是你问题的解决方案:
//Fetch page URL by this
$url = $_SERVER['REQUEST_URI'];
echo "$url<br />";
//It will print
//fetch host by this
$host=$_SERVER['HTTP_HOST'];
echo "$host<br />";
//You can fetch the full URL by this
$fullurl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $fullurl;
非常简单的用法:
function current_url() {
$current_url = ( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$current_url .= ( $_SERVER["SERVER_PORT"] != 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
$current_url .= $_SERVER["REQUEST_URI"];
return $current_url;
}