php 如何在 Windows/IIS 服务器上获取当前页面的完整 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/189113/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:51:46  来源:igfitidea点击:

How can I get the current page's full URL on a Windows/IIS server?

phpiis

提问by CtrlDot

I moved a WordPressinstallation to a new folder on a Windows/IISserver. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format:

我将WordPress安装移动到 Windows/ IIS服务器上的新文件夹。我正在 PHP 中设置 301 重定向,但它似乎不起作用。我的帖子 URL 具有以下格式:

http:://www.example.com/OLD_FOLDER/index.php/post-title/

I can't figure out how to grab the /post-title/part of the URL.

我不知道如何获取/post-title/URL的一部分。

$_SERVER["REQUEST_URI"]- which everyone seems to recommend - is returning an empty string. $_SERVER["PHP_SELF"]is just returning index.php. Why is this, and how can I fix it?

$_SERVER["REQUEST_URI"]- 每个人似乎都推荐 - 返回一个空字符串。$_SERVER["PHP_SELF"]刚回来index.php。这是为什么,我该如何解决?

采纳答案by Vinko Vrsalovic

Maybe, because you are under IIS,

也许,因为你在 IIS 下,

$_SERVER['PATH_INFO']

is what you want, based on the URLs you used to explain.

是你想要的,基于你用来解释的 URL。

For Apache, you'd use $_SERVER['REQUEST_URI'].

对于 Apache,您将使用$_SERVER['REQUEST_URI'].

回答by Tyler Carter

$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"];
}
return $pageURL;

回答by cwd

For Apache:

对于阿帕奇:

'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']


You can also use HTTP_HOSTinstead of SERVER_NAMEas Herman commented. See this related questionfor a full discussion. In short, you are probably OK with using either. Here is the 'host' version:


您也可以使用HTTP_HOST代替SERVER_NAME赫尔曼评论的那样。有关完整讨论,请参阅此相关问题。简而言之,您可能可以使用两者之一。这是“主机”版本:

'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']



For the Paranoid / Why it Matters

对于偏执狂 / 为什么它很重要

Typically, I set ServerNamein the VirtualHostbecause I want thatto be the canonicalform of the website. The $_SERVER['HTTP_HOST']is set based on the request headers. If the server responds to any/all domain names at that IP address, a user could spoof the header, or worse, someone could point a DNS record to your IP address, and then your server / website would be serving out a website with dynamic links built on an incorrect URL. If you use the latter method you should also configure your vhostor set up an .htaccessrule to enforce the domain you want to serve out, something like:

通常,我设置ServerNameVirtualHost因为我希望成为网站的规范形式。该$_SERVER['HTTP_HOST']基于请求头设置。如果服务器响应该 IP 地址上的任何/所有域名,则用户可能会欺骗标头,或者更糟的是,有人可能会将 DNS 记录指向您的 IP 地址,然后您的服务器/网站将提供动态网站建立在错误 URL 上的链接。如果您使用后一种方法,您还应该配置vhost或设置.htaccess规则来强制执行您要提供的域,例如:

RewriteEngine On
RewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$
RewriteRule (.*) https://stackoverflow.com/ [R=301,L]
#sometimes u may need to omit this slash ^ depending on your server

Hope that helps. The real point of this answer was just to provide the first line of code for those people who ended up here when searching for a way to get the complete URL with apache :)

希望有帮助。这个答案的真正意义只是为那些在寻找使用 apache 获取完整 URL 的方法时最终到达这里的人提供第一行代码:)

回答by Greg

$_SERVER['REQUEST_URI']doesn't work on IIS, but I did find this: http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/which sounds promising.

$_SERVER['REQUEST_URI']在 IIS 上不起作用,但我确实发现了这一点: http://neosmart.net/blog/2006/100-apache-compatible-request_uri-for-iis-and-windows/听起来很有希望。

回答by Sureshkumar

Use this class to get the URL works.

使用这个类来获取 URL 工作。

class VirtualDirectory
{
    var $protocol;
    var $site;
    var $thisfile;
    var $real_directories;
    var $num_of_real_directories;
    var $virtual_directories = array();
    var $num_of_virtual_directories = array();
    var $baseURL;
    var $thisURL;

    function VirtualDirectory()
    {
        $this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
        $this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];
        $this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);
        $this->real_directories = $this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['PHP_SELF'])));
        $this->num_of_real_directories = count($this->real_directories);
        $this->virtual_directories = array_diff($this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['REQUEST_URI']))),$this->real_directories);
        $this->num_of_virtual_directories = count($this->virtual_directories);
        $this->baseURL = $this->site . "/" . implode("/", $this->real_directories) . "/";
        $this->thisURL = $this->baseURL . implode("/", $this->virtual_directories) . "/";
    }

    function cleanUp($array)
    {
        $cleaned_array = array();
        foreach($array as $key => $value)
        {
            $qpos = strpos($value, "?");
            if($qpos !== false)
            {
                break;
            }
            if($key != "" && $value != "")
            {
                $cleaned_array[] = $value;
            }
        }
        return $cleaned_array;
    }
}

$virdir = new VirtualDirectory();
echo $virdir->thisURL;

回答by Avery

Add:

添加:

function my_url(){
    $url = (!empty($_SERVER['HTTPS'])) ?
               "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
               "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    echo $url;
}

Then just call the my_urlfunction.

然后只需调用该my_url函数。

回答by Jrgns

I use the following function to get the current, full URL. This should work on IIS and Apache.

我使用以下函数来获取当前的完整 URL。这应该适用于 IIS 和 Apache。

function get_current_url() {

  $protocol = 'http';
  if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {
    $protocol .= 's';
    $protocol_port = $_SERVER['SERVER_PORT'];
  } else {
    $protocol_port = 80;
  }

  $host = $_SERVER['HTTP_HOST'];
  $port = $_SERVER['SERVER_PORT'];
  $request = $_SERVER['PHP_SELF'];
  $query = isset($_SERVER['argv']) ? substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1) : '';

  $toret = $protocol . '://' . $host . ($port == $protocol_port ? '' : ':' . $port) . $request . (empty($query) ? '' : '?' . $query);

  return $toret;
}

回答by Peter Bailey

REQUEST_URI is set by Apache, so you won't get it with IIS. Try doing a var_dump or print_r on $_SERVER and see what values exist there that you can use.

REQUEST_URI 由 Apache 设置,因此您不会通过 IIS 获得它。尝试在 $_SERVER 上执行 var_dump 或 print_r 并查看可以使用的值。

回答by Adam Hopkinson

The posttitle part of the URLis after your index.phpfile, which is a common way of providing friendly URLs without using mod_rewrite. The posttitle is actually therefore part of the query string, so you should be able to get it using $_SERVER['QUERY_STRING']

URL的 posttitle 部分在您的index.php文件之后,这是不使用 mod_rewrite 提供友好 URL 的常用方法。因此,帖子标题实际上是查询字符串的一部分,因此您应该能够使用 $_SERVER['QUERY_STRING'] 获取它

回答by beniwal

Use the following line on the top of the PHP page where you're using $_SERVER['REQUEST_URI']. This will resolve your issue.

在您使用的 PHP 页面顶部使用以下行$_SERVER['REQUEST_URI']。这将解决您的问题。

$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];