Is $_SERVER['SERVER_ADDR'] always set?
Asked Answered
N

4

5

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

Nitpicking answered 10/8, 2011 at 22:51 Comment(0)
C
4

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()

Chandos answered 10/8, 2011 at 22:58 Comment(0)
T
4

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
Trainer answered 10/8, 2011 at 22:56 Comment(4)
And to make this absolutely certain to the dubious, there is a PHP Notice: PHP Notice: Undefined index: SERVER_ADDR in Command line code on line 1Cantrip
I wasn't convinced $_SERVER['SERVER_ADDR'] wasn't just an empty string so I decided to make sure :)Cantrip
Unset variables converted to strings are just an empty string. More strictly the variable is just NULL.Trainer
Ah, interesting. So undefined indexes are NULL :) I could have been more precise by saying I wanted to make sure isset($_SERVER['SERVER_ADDR']) === FALSECantrip
C
4

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()

Chandos answered 10/8, 2011 at 22:58 Comment(0)
H
1

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.

Huskey answered 10/8, 2011 at 23:18 Comment(0)
R
0

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());
Rivers answered 4/5, 2015 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.