php PHP获取域名

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

PHP get domain name

phpdomain-name

提问by Francisc

I want to get the domain name for where the script is running. How can that be done with PHP? I see that $_SERVER['HTTP_HOST']as well as $_SERVER['SERVER_NAME']contain this information. Will that variable always work and should I use one over the other?

我想获取运行脚本的域名。如何用 PHP 做到这一点?我看到$_SERVER['HTTP_HOST']$_SERVER['SERVER_NAME']包含此信息。该变量是否总是有效,我应该使用一个而不是另一个吗?

Thank you.

谢谢你。

回答by Mukesh Chapagain

Similar question has been asked in stackoverflow before.

之前在stackoverflow中也有人问过类似的问题。

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

请参阅此处:PHP $_SERVER['HTTP_HOST'] 与 $_SERVER['SERVER_NAME'],我是否正确理解手册页?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

另见这篇文章:http: //shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

推荐使用 HTTP_HOST,只有在没有设置 HTTP_HOST 时才回退到 SERVER_NAME。他说,由于多种原因,SERVER_NAME 在服务器上可能不可靠,包括:

  • 不支持 DNS
  • 配置错误
  • 负载均衡软件背后

来源http: //discussion.dreamhost.com/thread-4388.html

回答by xzyfer

To answer your question, these should work as long as:

要回答您的问题,只要满足以下条件,这些方法就应该有效:

  • Your HTTP server passes these values along to PHP (I don't know any that don't)
  • You're notaccessing the script via command line (CLI)
  • 您的 HTTP 服务器将这些值传递给 PHP(我不知道任何不知道的值)
  • 不是通过命令行 (CLI) 访问脚本

But, if I remember correctly, these values can be faked to an extent, so it's best not to rely on them.

但是,如果我没记错的话,这些值在一定程度上是可以伪造的,所以最好不要依赖它们。

My personal preference is to set the domain name as an environment variablein the apache2 virtual host:

我个人的偏好是在apache2虚拟主机中将域名设置为环境变量

# Virtual host
setEnv DOMAIN_NAME example.com

And read it in PHP:

在 PHP 中阅读

// PHP
echo getenv(DOMAIN_NAME);

This, however, isn't applicable in all circumstances.

然而,这并不适用于所有情况。