Created
January 21, 2019 22:55
-
-
Save ricardoalcocer/de1e2f1b718fee0bbf2044212ff1c69d to your computer and use it in GitHub Desktop.
PHP get real IP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://gist.github.com/irazasyed/6206195 | |
function get_ip_address() { | |
$ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'); | |
foreach ($ip_keys as $key) { | |
if (array_key_exists($key, $_SERVER) === true) { | |
foreach (explode(',', $_SERVER[$key]) as $ip) { | |
// trim for safety measures | |
$ip = trim($ip); | |
// attempt to validate IP | |
if (validate_ip($ip)) { | |
return $ip; | |
} | |
} | |
} | |
} | |
return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false; | |
} | |
/** | |
* Ensures an ip address is both a valid IP and does not fall within | |
* a private network range. | |
*/ | |
function validate_ip($ip) | |
{ | |
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { | |
return false; | |
} | |
return true; | |
} | |
echo get_ip_address(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment