$_SERVER['SERVER_ADDR'] 是否始终设置?

发布于 2024-11-29 03:10:20 字数 132 浏览 1 评论 0原文

$_SERVER['SERVER_ADDR'] 是否始终已设置?

我应该检查 isset() 还是没有必要?

我需要获取该站点的 IP,以便确定它是否为 127.0.0.1/localhost

Is $_SERVER['SERVER_ADDR'] always set?

Should I check with isset() or is that unnecessary?

I need to get the IP of the site so I can find out if it's 127.0.0.1/localhost

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

奈何桥上唱咆哮 2024-12-06 03:10:20

它不会总是被设置。考虑一下您甚至可以在没有服务器的情况下安装 PHP 并从命令行运行它。任何 $_SERVER 变量都不能保证,但如果您在服务器上尝试一次并且它有效,那么您可以打赌它将始终在该服务器配置上设置。您只需要在某处记下,如果您对服务器的配置进行了重大更改,或者切换了服务器,您应该再次检查。

您还可以使用 phpinfo() 检查服务器变量的值

It's not going to always be set. Consider that you can install PHP without even having a server and run it from command line. There is no guarantee with any of the $_SERVER variables, but if you try it once on your server and it works then you can bet that it will always be set on that server configuration. You just need to make a note somewhere that if you ever do a major change on your server's configuration, or switch servers you should check it again.

You can also check the value of your server variables with phpinfo()

梦亿 2024-12-06 03:10:20

不,在 CLI 中它没有设置。所以并不总是如此。

$ php -r "echo $_SERVER['SERVER_ADDR'];"

(无输出)

如果您记录或报告了错误(基于您的 PHP.ini 设置),您也会收到此消息:

PHP Notice: Undefined index: SERVER_ADDR in Command line code on line 1

No, in CLI it's not set. So not always.

$ php -r "echo $_SERVER['SERVER_ADDR'];"

(no output)

If you have errors logged or reported (based on your PHP.ini settings), you will get this message as well:

PHP Notice: Undefined index: SERVER_ADDR in Command line code on line 1
吾性傲以野 2024-12-06 03:10:20

CLI 是未设置的一个很好的示例,但所有 _SERVER 值都是由运行 php 的服务器设置的,因此根据您使用的服务器及其配置,无法保证无论如何它都会被设置。

CLI is a good example of when it's not set, but all of the _SERVER values are set by the server that php is running on, so depending upon the server you are using and its configuration, there's no guarantee that it will be set anyway.

梦行七里 2024-12-06 03:10:20

正如之前通过 cli 所说,它不可用。
如果您需要通过 cli 或 HTTP 调用了解 IP 地址,请考虑使用如下所示的内容:

$IP = isset($_SERVER['SERVER_ADDR'])?$_SERVER['SERVER_ADDR']:gethostbyname(gethostname());

As previously said via cli it's not available.
Just in case you need to know the IP address both via cli or via HTTP call consider using something like following:

$IP = isset($_SERVER['SERVER_ADDR'])?$_SERVER['SERVER_ADDR']:gethostbyname(gethostname());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文