<?php

declare (strict_types = 1);
namespace library\utils;
// +----------------------------------------------------------------------
// | [ 工具类-常用操作  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-29 20:41
// +----------------------------------------------------------------------

use library\utils\Http;

class UtilsTool
{
    /**
     * ip地址转区域
     * @param type $ip
     */
    static public function ipToArea($ip=''){
        $timeout = 60;
        $http_header = array(
            'content-type:application/json;charset=utf8'
        );
        $ip=urlencode($ip);
        $url = "http://ip.ws.126.net/ipquery?ip={$ip}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        if(!mb_check_encoding($result, "utf-8")){
            $result = mb_convert_encoding($result,'UTF-8',['ASCII','UTF-8','GB2312','GBK']);
        }
        if(!empty($result)){
            $result = trim($result);
            if(empty($result)){
                return false;
            }
            $result = explode("localAddress=", $result);
            if(empty($result) || count($result)<2){
                return false;
            }
            $jsonStr = $result[1];
            $jsonStr = str_replace("city", '"city"', $jsonStr);
            $jsonStr = str_replace("province", '"province"', $jsonStr);
            $jsonStr = str_replace(" ", "", $jsonStr);
            if(empty($jsonStr)){
                return false;
            }
            return @json_decode($jsonStr,true);
        }else{
            return false;
        }
    }
}