Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Last active December 19, 2015 12:04
Show Gist options
  • Save eyecatchup/5764719 to your computer and use it in GitHub Desktop.
Save eyecatchup/5764719 to your computer and use it in GitHub Desktop.
<?php
function getClientIP() {
$ip = null;
//check ip from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
//to check ip is pass from proxy
else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// HTTP_X_FORWARDED_FOR might return multiple IPs!
// The first IP may be the real client behind many proxies,
// but it can be fake (modified through headers).
// So what is correct is to get the LAST IP from the list of IPs,
// which is the IP that connected to your (reverse) proxy
$xff = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = (false !== strpos($xff, ',')) ? end(explode(',', $xff)) : $xff;
}
else if (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
// CLI safe version:
function getClientIP() {
$ip = null;
if (isset($_SERVER)) {
//check ip from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
//to check ip is pass from proxy
else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// HTTP_X_FORWARDED_FOR might return multiple IPs!
// The first IP may be the real client behind many proxies,
// but it can be fake (modified through headers).
// So what is correct is to get the LAST IP from the list of IPs,
// which is the IP that connected to your (reverse) proxy
$xff = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = (false !== strpos($xff, ',')) ? end(explode(',', $xff)) : $xff;
}
else if (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
}
else {
//check ip from share internet
if (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
}
//to check ip is pass from proxy
else if (getenv('HTTP_X_FORWARDED_FOR')) {
// HTTP_X_FORWARDED_FOR might return multiple IPs!
// The first IP may be the real client behind many proxies,
// but it can be fake (modified through headers).
// So what is correct is to get the LAST IP from the list of IPs,
// which is the IP that connected to your (reverse) proxy
$xff = getenv('HTTP_X_FORWARDED_FOR');
$ip = (false !== strpos($xff, ',')) ? end(explode(',', $xff)) : $xff;
}
else if (getenv('REMOTE_ADDR')) {
$ip = getenv('REMOTE_ADDR');
}
}
return $ip;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment