Function to get the user's IP address

Possible duplicate:
What is the most accurate way to get the correct IP address of a user in PHP?

Is there a better function in php to get user IP address? this is what i am using at the moment

function GetIP() { if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR"); else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR']; else $ip = "unknown"; return($ip); } 
+11
php
Jul 16 2018-11-11T00:
source share
2 answers

Well, your function should behave as expected, but here are a few tips:

 // lowercase first letter of functions. It is more standard for PHP function getIP() { // populate a local variable to avoid extra function calls. // NOTE: use of getenv is not as common as use of $_SERVER. // because of this use of $_SERVER is recommended, but // for consistency, I'll use getenv below $tmp = getenv("HTTP_CLIENT_IP"); // you DON'T want the HTTP_CLIENT_ID to equal unknown. That said, I don't // believe it ever will (same for all below) if ( $tmp && !strcasecmp( $tmp, "unknown")) return $tmp; $tmp = getenv("HTTP_X_FORWARDED_FOR"); if( $tmp && !strcasecmp( $tmp, "unknown")) return $tmp // no sense in testing SERVER after this. // $_SERVER[ 'REMOTE_ADDR' ] == gentenv( 'REMOTE_ADDR' ); $tmp = getenv("REMOTE_ADDR"); if($tmp && !strcasecmp($tmp, "unknown")) return $tmp; return("unknown"); } 
+10
Jul 16 2018-11-14T00:
source share

Adapted from this answer :

 function GetIP() { foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) { if (array_key_exists($key, $_SERVER) === true) { foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) { return $ip; } } } } } 

Checks IP addresses (in order) at:

  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED
  • REMOTE_ADDR

Remember that the only IP address you can trust is the one that comes from $_SERVER['REMOTE_ADDR'] .

+32
Jul 16 2018-11-11T00:
source share



All Articles