Skip to content

Instantly share code, notes, and snippets.

@croxton
Created September 13, 2012 16:59
Show Gist options
  • Save croxton/3715803 to your computer and use it in GitHub Desktop.
Save croxton/3715803 to your computer and use it in GitHub Desktop.
./system/codeigniter/system/core/Input.php function ip_address()
/**
* Fetch the IP Address
*
* @access public
* @return string
*/
public function ip_address()
{
if ($this->ip_address !== FALSE)
{
return $this->ip_address;
}
if (config_item('proxy_ips') != '' && $this->server('HTTP_X_FORWARDED_FOR') && $this->server('REMOTE_ADDR'))
{
$has_ranges = strpos($proxies, '/') !== false;
$proxies = preg_split('/[\s,]/', config_item('proxy_ips'), -1, PREG_SPLIT_NO_EMPTY);
$proxies = is_array($proxies) ? $proxies : array($proxies);
if ($has_ranges)
{
$long_ip = ip2long($_SERVER['REMOTE_ADDR']);
$bit_32 = 1 << 32;
// Go through each of the IP Addresses to check for and
// test against range notation
foreach($proxies as $ip)
{
list($address, $mask_length) = explode('/', $ip);
// Generate the bitmask for a 32 bit IP Address
$bitmask = $bit_32 - (1 << (32 - (int)$mask_length));
if (($long_ip & $bitmask) == $address)
{
$this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
break;
}
}
}
else
{
$this->ip_address = in_array($_SERVER['REMOTE_ADDR'], $proxies) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
}
}
elseif ($this->server('HTTP_CLIENT_IP'))
{
$this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
}
elseif ($this->server('HTTP_X_FORWARDED_FOR'))
{
$this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
elseif ($this->server('REMOTE_ADDR'))
{
$this->ip_address = $_SERVER['REMOTE_ADDR'];
}
if ($this->ip_address === FALSE)
{
return $this->ip_address = '0.0.0.0';
}
if (strpos($this->ip_address, ',') !== FALSE)
{
$x = explode(',', $this->ip_address);
$this->ip_address = trim(end($x));
}
if ( ! $this->valid_ip($this->ip_address))
{
return $this->ip_address = '0.0.0.0';
}
return $this->ip_address;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment