Write the Code. Change the World.

4月 25

// 将 ip 转换成 city
function ip2City($ip)
{
    $url = "https://apis.map.qq.com/ws/location/v1/ip?ip={$ip}&key=XXXXXXXX";
    $res = curl($url, false, false, true);
    $data = [];

    try {
        if ($res) {
            $res = json_decode($res, true);
        }

        if ($res && $res['status'] == 0 && $res['result']) {
            $data['latitude'] =  $res['result']['location']['lat'];
            $data['longitude'] =  $res['result']['location']['lng'];
            $data['city'] =  $res['result']['ad_info']['city'] ? $res['result']['ad_info']['city'] : '未知';
            $data['citycode'] =  $res['result']['ad_info']['adcode'] && $res['result']['ad_info']['adcode'] > 0 ? $res['result']['ad_info']['adcode'] : 0;
        }
    } catch (Exception $e) {
    }
    return $data;
}

/**
 * @param string $url 请求网址
 * @param bool $params 请求参数
 * @param bool $post 请求方式,是否是post
 * @param bool $https 请求http协议,是否是https
 * @return bool|mixed
 */
function curl($url, $params = false, $post = false, $https = false)
{
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if ($post === true) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params === false) {
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if (is_array($params)) {
                $params = http_build_query($params);
            }
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        }
    }

    if ($https === true) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    }
    $response = curl_exec($ch);
    if ($response === false) {
        Illuminate\Support\Facades\Log::error(sprintf('curl 错误。 url:%s, error:%s', $url, curl_error($ch)));
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注