| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- /**
- * IP查询服务
- * @author wesmielr
- */
- namespace app\index\service;
- class IpService
- {
- /**
- * 获取IP对应地址
- * @param $ip IP
- * @param $format 返回数据格式:1-直接返回地址,2-返回数组
- * @return array|bool
- */
- public static function getAddress($ip, $format = 1){
- $urls = config('api.urls');
- if(empty($urls) || empty($ip)){
- return false;
- }
- $cacheKey = "address:ip:".$ip.'_'.$format;
- $result = RedisService::get($cacheKey);
- $data = isset($result['data'])? trim( $result['data']) : '';
- if(!empty($data)){
- return $data;
- }
- // 解析获取地址
- foreach ($urls as $key => $apiUrl){
- $apiUrl = sprintf($apiUrl, $ip);
- $result = httpGet($apiUrl,'array',5);
- $data = self::getResult($key, $result, $format);
- if(!empty($data)){
- RedisService::set($cacheKey, ['apiUrl'=> $apiUrl, 'data'=> $data], 7*24*3600);
- return $data;
- }
- }
- return false;
- }
- /**
- * 解析结果数据
- * @param $apiName 接口名称
- * @param $result 接口返回数据
- * @return array
- */
- private static function getResult($apiName, $result, $format){
- switch ($apiName){
- case 'pconline': // 太平洋
- $address = [];
- if(isset($result['pro'])){
- $address[] = isset($result['pro'])? $result['pro'] : '';
- }
- if(isset($result['city'])){
- $address[] = isset($result['city'])? $result['city'] : '';
- }
- return $format==1 && $address? implode(' ', $address) : $result;
- break;
- case 'taobao': // 淘宝
- $address = [];
- $result = isset($result['data'])? $result['data'] : [];
- if(isset($result['region'])){
- $address[] = isset($result['region'])? $result['region'] : '';
- }
- if(isset($result['city'])){
- $address[] = isset($result['city'])? $result['city'] : '';
- }
- return $format==1 && $address? implode(' ', $address) : $result;
- break;
- default: // 默认
- return $format==1? (isset($result['city'])? $result['city'] : '') : $result;
- }
- }
- }
|