IT培训网 - IT职场人学IT技术上IT培训网
浅析php如何获取客户端IP真实地址和归属地
时间:2017-07-08 13:23:32 来源:php培训网 作者:IT培训网 已有:名学员访问该课程
php如何获取客户端IP真实地址和归属地?接下来我们就简单分析一下。
//代码如下:
<?php
/*获取客户端真实的IP*/
function GetIps(){
$realip = '';
$unknown = 'unknown';
if (isset($_SERVER)){
if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])
&& strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach($arr as $ip){
$ip = trim($ip);
if ($ip != 'unknown'){
$realip = $ip;
break;
}
}
}else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) &&
strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){
$realip = $_SERVER['HTTP_CLIENT_IP'];
}else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR'])
&& strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){
$realip = $_SERVER['REMOTE_ADDR'];
}else{
$realip = $unknown;
}
}else{
if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){
$realip = getenv("HTTP_X_FORWARDED_FOR");
}else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){
$realip = getenv("HTTP_CLIENT_IP");
}else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){
$realip = getenv("REMOTE_ADDR");
}else{
$realip = $unknown;
} }
$realip = preg_match("/[d.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
return $realip; }
/*把IP传入新浪API返回数据获取ip的真实归属地*/
function GetIpFrom($ip = ''){
if(empty($ip)){
$ip = GetIps();
}
$res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip='.$ip);
if(empty($res)){ return false; }
$jsonMatches = array();
preg_match('#{.+?}#', $res, $jsonMatches);
if(!isset($jsonMatches[0])){ return false; }
$json = json_decode($jsonMatches[0], true);
if(isset($json['ret']) && $json['ret'] == 1){
$json['ip'] = $ip;
unset($json['ret']);
}else{
return false;
}
$address[0] = $json['country'].$json['province'].$json['city']
.$json['district'].$json['isp'].$json['type'].$json['desc'];
$address[1] = $json['ip'];
return $address;
}
//返回客户端的ip地址和归属地信息。
上面代码用的是新浪API。
每期开班座位有限.0元试听抢座开始!
温馨提示 : 请保持手机畅通,咨询老师为您
提供专属一对一报名服务。
- 上一篇:天津PHP培训怎么样 天津PHP培训深得人心
- 下一篇:汇总php中所有的错误说明