获取整个 URL,包括查询字符串和锚点

php
2022-08-30 11:07:00

有没有办法在包含的页面中获取用于请求当前页面的整个URL,包括锚点(- I可能使用了错误的单词之后的文本)?#

即页面 foo.php 包含在 bar.php 中。如果我在foo.php中使用您的解决方案,我需要它说.bar.php?blarg=a#example


答案 1

不,恐怕不是,因为哈希(包括#在内的字符串)永远不会传递到服务器,它只是浏览器的行为属性。但是,该变量将包含其余部分。$_SERVER['REQUEST_URI']

如果您确实需要知道哈希是什么,则必须使用JavaScript属性,其中包含哈希的内容(然后可以将其插入表单中,或者将其发送到带有ajax请求的服务器)。document.location.hash


答案 2
// find out the domain:
$domain = $_SERVER['HTTP_HOST'];
// find out the path to the current file:
$path = $_SERVER['SCRIPT_NAME'];
// find out the QueryString:
$queryString = $_SERVER['QUERY_STRING'];
// put it all together:
$url = "http://" . $domain . $path . "?" . $queryString;
echo $url;

// An alternative way is to use REQUEST_URI instead of both
// SCRIPT_NAME and QUERY_STRING, if you don't need them seperate:
$url = "http://" . $domain . $_SERVER['REQUEST_URI'];
echo $url;

推荐