1. 程式人生 > >PHP開發小技巧②③—根據ip地址獲取城市

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" => '北京市'
        );
    }
}