views:

211

answers:

5

What is the better way of getting the IP address in PHP:

getenv('REMOTE_ADDR');

or,

$_SERVER['REMOTE_ADDR'];

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

+1  A: 

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

The common approach is to use $_SERVER for this, although it doesn't really make a difference functionality-wise.

reko_t
+9  A: 

$_SERVER is a built in PHP variable, while getenv() ask the environment (probably Apache/IIS) for values.

The best way to get the IP is;

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

But I doubt there's any difference between these two variables... Hm.

Björn
+1  A: 

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

Henri Watson
+1  A: 

There's no differences between the tho calls. As you can see PHP manual use both method in the same example. There are some cases where you don't have global variables like $_SERVER enabled and you are forced to use getenv(). In my experience i've never seen a server with global variables disabled.

wezzy
A: 
BitDrink