Which is the best way to get ip

What is the best way to get IP address in PHP:

getenv('REMOTE_ADDR'); 

or,

 $_SERVER['REMOTE_ADDR']; 

please tell me the difference, if any, between them.

+4
source share
5 answers

getenv () can be used to access any environment variables (PHP simply registers REMOTE_ADDR as the environment variable for the script), while with $ _SERVER you obviously only get access to the contents of the supergellon $ _SERVER.

The general approach is to use $ _SERVER for this, although in reality it does not have a difference in functionality.

+3
source

$ _ SERVER is a PHP built-in variable, and getenv () queries the environment (possibly Apache / IIS) for the values.

The best way to get the IP address:

 $ip = (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : getenv('REMOTE_ADDR'); 

But I doubt that the difference between these two variables ... Hm.

+11
source

It would probably be better to use $ _SERVER ['REMOTE_ADDR']; to prevent incompatibility between servers.

+1
source

There are no differences between calls. As you can see the PHP manual , use both methods in the same example. There are times when you do not have global variables such as $ _SERVER, and you are forced to use getenv (). In my experience, I have never seen a server with global variables shut down.

+1
source

With $_SERVER['REMOTE_ADDR'] you read the global variable directly, referring to the $ _SERVER [] array, which is configured when a remote request occurs:

$ _ SERVER is an array containing information such as the headers, paths, and locations of the script. The entries in this array are created by the web server. There is no guarantee that each web server will provide any of these; servers may omit some or provide to others not listed here. However, a large number of these variables are considered in the "CGI 1.1" specification, so you can expect them.

The getenv () function accesses any environment variable to get the corresponding value!

In both cases, you get the same value and the same variable ... but $ _SERVER is the assembly in the PHP superglobal variable, and getenv () gets the value of the variable defined in the current environment!

I think that in this case, using a superglobal variable is the best way to get the IP address!

0
source

All Articles