您现在的位置是:网站首页 > 脚本编程>

根据IP地址获取访问者所在的城市

2015-08-11890人围观
简介 当我们在页面中填写个人资料中的省市信息时,页面会根据当前用户所在的城市自动选中省市下拉选项;当我们访问某个大型站点时,网站程序会自动进入到用户当前所在的城市频道。这些功能是如何实现的呢?今天我们来通过实例讲解如何根据IP定位用户所在城市信息。

根据ip获取当前所在的城市,这种功能大多用在城市分站中,最近小编做了一个给大家分享一下:


1、获取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;
    }

2、根据ip地址获取所在的城市

function GetIpLookup($ip = '') {
        if (empty($ip)) {
            $ip = GetIp();
        }
        $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;
        }
        return $json;

    }

效果图:


打赏本站,你说多少就多少

精彩评论

微信关注

Copyright © 2013-2019 千奇博客 保留所有权利 辽ICP备13008238号