两种PHP写法获取客户端真实IP方法:
0 1 2 3 4 5 6 7 8 9 10 |
function getip(){ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $realip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $realip = $_SERVER['HTTP_CLIENT_IP']; } else { $realip = $_SERVER['REMOTE_ADDR']; } return $realip; } |
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function getIP() { $unknown = 'unknown'; if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) { $ip = $_SERVER['REMOTE_ADDR']; } /* 处理多层代理的情况 或者使用正则方式:$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown; */ if (false !== strpos($ip, ',')) $ip = reset(explode(',', $ip)); return $ip; } |
本地测试获取的IP一般为::1这是正常的,在远程服务器中此方法是可用的
Host映射查看方法 C:\Windows\System32\drivers\etc 文件hosts
由于客户端可以篡改IP,所以在使用此方法获取的IP要进行过滤。
下面是获取到的客户端IP再获取客户端的地理信息(省份、地区、经纬度)
0 1 2 3 4 5 6 7 8 9 10 11 12 |
function getInfo(){ $getIp='116.255.222.22'; $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=7IZ6fgGEGohCrRKUE9Rj4TSQ&ip={$getIp}&coor=bd09ll"); $json = json_decode($content); echo '<br/>'; echo 'log:',$json->{'content'}->{'point'}->{'x'};//按层级关系提取经度数据 echo '<br/>'; echo 'lat:',$json->{'content'}->{'point'}->{'y'};//按层级关系提取纬度数据 echo '<br/>'; print $json->{'content'}->{'address'};//按层级关系提取address数据 echo '<br/>'; } |