本篇文章给大家分享的内容是php开发小技巧之根据ip地址获取城市 ,有着一定的参考价值,有需要的朋友可以参考一下
这个方法我们用的还是比较多的,便于收集信息用于数据挖掘分析。此方法不光根据ip地址进行获取当前城市还可以根据http请求获取用户的城市位置。
实现方法:主要是根据高德地图api进行获取,首先注册成为高德地图用户,然后认证成为开发者,创建应用获取key进行调用即可。具体实现方法如下:
<?php
/**
* =======================================
* created by zhihua·wei.
* author: zhihua·wei
* date: 2018/4/12
* time: 16:13
* project: php开发小技巧
* power: 根据ip地址获取城市
* =======================================
*/
/**
* 根据http请求获取用户位置
*/
function get_user_location()
{
$key = "4a218d0d82c3a74acf019b701e8c0ccc"; // 高德地图key
$url = "http://restapi.amap.com/v3/ip?key=$key";
$json = file_get_contents($url);
$obj = json_decode($json, true); // 转换数组
$obj["message"] = $obj["status"] == 0 ? "失败" : "成功";
return $obj;
}
/**
* 根据 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' => '4a218d0d82c3a74acf019b701e8c0ccc',
'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 (count($res['province']) == 0) {
$res['province'] = '北京市';
}
if (!empty($res['province']) && $res['province'] == "局域网") {
$res['province'] = '北京市';
}
if (count($res['city']) == 0) {
$res['city'] = '北京市';
}
} else {
$res['province'] = '北京市';
$res['city'] = '北京市';
}
return $res;
} else {
return array(
"province" => '北京市',
"city" => '北京市'
);
}
}
相关推荐:
php开发小技巧之判断是否微信访问
以上就是php开发小技巧之根据ip地址获取城市 的详细内容。