Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Created May 26, 2013 19:36
Show Gist options
  • Save ranaroussi/5653786 to your computer and use it in GitHub Desktop.
Save ranaroussi/5653786 to your computer and use it in GitHub Desktop.
Get client's real IP
function get_client_ip() {
$check_order = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
$reserved_ips = 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')
);
for($i=0; $i<count($check_order); $i++) {
$item = $check_order[$i];
if (isset($_SERVER[$item])) {
$lineitem = explode(',', $_SERVER[$item]);
$ip = trim($lineitem[0]);
// check its not an internal ip
if (!empty($ip) && ip2long($ip) != -1) {
foreach ($reserved_ips as $r) {
$min = ip2long($r[0]);
$max = ip2long($r[1]);
if ((ip2long($ip) >= $min) && (ip2long($ip) <= $max)) {
return null;
}
}
return $ip;
}
}
}
return null;
}
@djchateau
Copy link

I'm confused why you wouldn't get this directly through one of PHP's session variables?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment