PHP根据IP获取城市名称

PHP根据IP获取城市名称

/**
 * 根据 ip 获取 当前城市
 */
function get_city_by_ip()
{
	if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
		$cip = $_SERVER["HTTP_CLIENT_IP"];
	} elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
		$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	} elseif (!empty($_SERVER["REMOTE_ADDR"])) {
		$cip = $_SERVER["REMOTE_ADDR"];
	} else {
		$cip = "";
	}
	$url = 'https://restapi.amap.com/v3/ip';
	$data = array(
		'output' => 'json',
		'key' => '16199cf2aca1fb54d0db495a3140b8cb',
		'ip' => $cip
	);
	
	$postdata = http_build_query($data);
	$opts = array(
		'http' => array(
			'method' => 'POST',
			'header' => 'Content-type: application/x-www-form-urlencoded',
			'content' => $postdata
		)
	);
	
	$context = stream_context_create($opts);
	
	$result = file_get_contents($url, false, $context);
	
	if (!empty($result)) {
		$res = json_decode($result, true);
		
		if (!empty($res)) {
			
			if (empty($res['province'])) {
				$res['province'] = '北京市';
			}
			if (!empty($res['province']) && $res['province'] == "局域网") {
				$res['province'] = '北京市';
			}
			
			if (is_array($res['province'])) {
				$province_count = count($res['province']);
				if ($province_count == 0) {
					$res['province'] = '北京市';
				}
			}
			if (is_array($res['city'])) {
				$city_count = count($res['city']);
				if ($city_count == 0) {
					$res['city'] = '北京市';
				}
			}
		} else {
			$res['province'] = '北京市';
			$res['city'] = '北京市';
		}
		
		return $res;
	} else {
		return array(
			"province" => '北京市',
			"city" => '北京市'
		);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值