Created
March 10, 2019 04:59
-
-
Save onyxhat/fa2abd3cf56d6b67bf0069b4af6b74b3 to your computer and use it in GitHub Desktop.
simple PHP script to return client IP address
This file contains 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 | |
/** | |
* 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; | |
} | |
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; | |
} | |
echo get_ip_address(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment