Skip to content

Instantly share code, notes, and snippets.

@Sanix-Darker
Last active September 23, 2017 20:46
Show Gist options
  • Save Sanix-Darker/c99e258c000528adefdd624ffac7899c to your computer and use it in GitHub Desktop.
Save Sanix-Darker/c99e258c000528adefdd624ffac7899c to your computer and use it in GitHub Desktop.
[PHP] Get IP adress of the visitor
<?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;
}
/**
* To return the Ip Adress
*/
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;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment