Skip to content

Instantly share code, notes, and snippets.

@jas-
Created January 9, 2012 17:45
Show Gist options
  • Save jas-/1584075 to your computer and use it in GitHub Desktop.
Save jas-/1584075 to your computer and use it in GitHub Desktop.
Retreive 'real' IP of remote clients
/**
* @function _getRealIPv4
* @abstract Try all methods of obtaining 'real' IP address
*/
function _getRealIPv4()
{
return (getenv('HTTP_CLIENT_IP') && $this->_ip(getenv('HTTP_CLIENT_IP'))) ?
getenv('HTTP_CLIENT_IP') :
(getenv('HTTP_X_FORWARDED_FOR') && $this->_forwarded(getenv('HTTP_X_FORWARDED_FOR'))) ?
$this->_forwarded(getenv('HTTP_X_FORWARDED_FOR')) :
(getenv('HTTP_X_FORWARDED') && $this->_ip(getenv('HTTP_X_FORWARDED'))) ?
getenv('HTTP_X_FORWARDED') :
(getenv('HTTP_X_FORWARDED_HOST') && $this->_ip(getenv('HTTP_FORWARDED_HOST'))) ?
getenv('HTTP_X_FORWARDED_HOST') :
(getenv('HTTP_X_FORWARDED_SERVER') && $this->_ip(getenv('HTTP_X_FORWARDED_SERVER'))) ?
getenv('HTTP_X_FORWARDED_SERVER') :
(getenv('HTTP_X_CLUSTER_CLIENT_IP') && $this->_ip(getenv('HTTP_X_CLIUSTER_CLIENT_IP'))) ?
getenv('HTTP_X_CLUSTER_CLIENT_IP') :
getenv('REMOTE_ADDR');
}
/**
* @function _ip
* @abstract Attempts to determine if IP is non-routeable
*/
function _ip($ip)
{
if (!empty($ip) && ip2long($ip)!=-1 && ip2long($ip)!=false){
$nr = array(array('0.0.0.0','2.255.255.255'),
array('10.0.0.0','10.255.255.255'),
array('127.0.0.0','127.255.255.255'),
array('169.254.0.0','169.254.255.255'),
array('172.16.0.0','172.31.255.255'),
array('192.0.2.0','192.0.2.255'),
array('192.168.0.0','192.168.255.255'),
array('255.255.255.0','255.255.255.255'));
foreach($nr as $r){
$min = ip2long($r[0]);
$max = ip2long($r[1]);
if ((ip2long($ip) >= $min) && (ip2long($ip) <= $max)) return false;
}
return true;
} else {
return false;
}
}
/**
* @function _forwarded
* @abstract A helper for HTTP_X_FORWARDED_FOR, loops over comma
* separated list of proxies associated with request
*/
function _forwarded($l)
{
if (!empty($l)){
foreach (explode(',', $l) as $i){
if (_ip(trim($i))) {
return (!_ip(trim($i))) ? false : $i;
}
}
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment