Home > Article > Backend Development > PHP development tips: Get the city based on the IP address
The content shared with you in this article is PHP development tips for obtaining the city based on the IP address. It has a certain reference value. Friends in need can refer to it
We still use this method quite a lot to facilitate the collection of information for data mining analysis. This method not only obtains the current city based on the IP address, but also obtains the user's city location based on the HTTP request.
Implementation method: Mainly obtain it based on the Amap API. First register as an Amap user, then authenticate as a developer, create an application and obtain the key for calling. The specific implementation method is as follows:
<?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" => '北京市' ); } }
Related recommendations:
Tips for PHP development: Determining whether it is WeChat access
The above is the detailed content of PHP development tips: Get the city based on the IP address. For more information, please follow other related articles on the PHP Chinese website!