Article

分享经验与智慧

phpcms根据ip获取所在城市信息

发表时间:2019-12-27 13:30:27

文章来源:星诺网络

标签: phpcms  获取  所在 

分享:

首先:找到phpcms/libs/classes/ip_area.class.php,
增加代码:
function get_area($ip = ''){
    if($ip == ''){
        $ip = GetIp();
    }
    $url = "http://ip.taobao.com/service/getIpInfo.php?ip={$ip}";
pc_base::load_sys_func('iconv');
    $ret = https_request($url);
    $arr = json_decode($ret,true);
    return $arr;
    }
 
 
//POST请求函数
 
 
// 获取ip
function GetIp(){
    $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;
}


其次,在phpcms/libs/functions/iconv.func.php,
增加代码;
 function https_request($url,$data = null){
    $curl = curl_init();
     
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
     
    if(!empty($data)){//如果有数据传入数据
        curl_setopt($curl,CURLOPT_POST,1);//CURLOPT_POST 模拟post请求
        curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//传入数据
    }
     
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    $output = curl_exec($curl);
    curl_close($curl);
     
    return $output;
}

最后,去调用的地方,调用一下即可。
代码如下:
<?php $city = $ip_area->get_area($d['ip']);
$citys = $city['data'];
echo $citys['country'].'-'.$citys['region'].'-'.$citys['city'].'-'.$citys['isp'].'- ip:'.$d['ip'];
?>

效果如下:


石家庄网站建设,石家庄UI设计公司,网页切图,企业网站制作,营销型网站建设,专业做网站,响应式网站建设,石家庄网站制作,石家庄网站开发,石家庄建网站公司

相关案例查看更多

填写需求:

*提交完,稍后会有客服与您联系的。