Procedural php script to get visitor ip
<?php
// If ip comes from behind proxy server
function forwarded_ip() {
$keys = array(
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'HTTP_CLIENT_IP',
'HTTP_X_CLUSTER_CLIENT_IP'
);
foreach ($keys as $key) {
if(isset($_SERVER[$key])) {
$ip_array = explode(',', $_SERVER[$key]);
foreach ($ip_array as $ip) {
$ip = trim($ip);
if(validate_ip($ip)) {
return $ip;
}
}
}
}
return '';
}
// Check is ip valid
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;
} else {
return true;
}
}
$forwarded_ip = forwarded_ip();
$remote_ip = $_SERVER['REMOTE_ADDR'];
$the_ip = "";
// Check and use ip, forwarded or remote
if($forwarded_ip != '') {
$the_ip = $forwarded_ip;
} else {
$the_ip = $remote_ip;
}
echo $the_ip;