根据IP获得城市信息(百度API的运用)

/**
     * 根据IP获取城市
     * @param string $ip ip地址
     * @return array
     * http://api.map.baidu.com/location/ip?ak=32f38c9491f2da9eb61106aaab1e9739&ip="+ip
     */
    public function getCityByIp($ip)
    {
        $result = false;
        $url =  "http://api.map.baidu.com/location/ip?ak=32f38c9491f2da9eb61106aaab1e9739&ip=".$ip;
        $result = file_get_contents($url);
        $result = json_decode($result);
        $result = self::objtoarr($result);
        if (is_array($result) && isset($result['status'])) {
            if ($result['status'] == 0 && isset($result['content'])) {
                $result['city'] = iconv('utf-8', 'gbk', $result['content']['address_detail']['city']);
            }
        }
        return $result;
    }
    /**
     * 将对象类型数据转化为数组形式
     * @param stdClass Object $obj 对象类型数据
     * @return array
     */
    public static function objtoarr($obj)
    {
        $ret = array();
        foreach ($obj as $key =>$value) {
            if (gettype($value) == 'array' || gettype($value) == 'object') {
                $ret[$key] = self::objtoarr($value);
            } else {
                $ret[$key] = $value;
            }
        }
        return $ret;
    }

/**
* 获取客户端IP地址
* @param boolean $pasportlogin 是否是passport登录
* @param boolean $forwarded    是否取HTTP_X_FORWARDED_FOR
* @return string
*/
function Get_Client_ip($pasportlogin = true, $forwarded = false)
{
    if (getenv("HTTP_X_REAL_IP") && strcasecmp(getenv("HTTP_X_REAL_IP"), "unknown") && !$forwarded)
        $ip = getenv("HTTP_X_REAL_IP");
    else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";

if ($pasportlogin === true) {
        if (false !== strpos($ip, ',')) {
            $arrIp = explode(', ', $ip);
            for ($i = 0; $i < count($arrIp); $i++) {
                if (!eregi("^(10|172\.16|192\.168)\.", $arrIp[$i])) {
                    $ip = $arrIp[$i];
                    break;
                }
            }
        }
    }

return($ip);
}

上一篇:转"container of()函数简介"链接地址


下一篇:Python之美[从菜鸟到高手]--深刻理解原类(metaclass)