IpService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * IP查询服务
  4. * @author wesmielr
  5. */
  6. namespace app\index\service;
  7. class IpService
  8. {
  9. /**
  10. * 获取IP对应地址
  11. * @param $ip IP
  12. * @param $format 返回数据格式:1-直接返回地址,2-返回数组
  13. * @return array|bool
  14. */
  15. public static function getAddress($ip, $format = 1){
  16. $urls = config('api.urls');
  17. if(empty($urls) || empty($ip)){
  18. return false;
  19. }
  20. $cacheKey = "address:ip:".$ip.'_'.$format;
  21. $result = RedisService::get($cacheKey);
  22. $data = isset($result['data'])? trim( $result['data']) : '';
  23. if(!empty($data)){
  24. return $data;
  25. }
  26. // 解析获取地址
  27. foreach ($urls as $key => $apiUrl){
  28. $apiUrl = sprintf($apiUrl, $ip);
  29. $result = httpGet($apiUrl,'array',5);
  30. $data = self::getResult($key, $result, $format);
  31. if(!empty($data)){
  32. RedisService::set($cacheKey, ['apiUrl'=> $apiUrl, 'data'=> $data], 7*24*3600);
  33. return $data;
  34. }
  35. }
  36. return false;
  37. }
  38. /**
  39. * 解析结果数据
  40. * @param $apiName 接口名称
  41. * @param $result 接口返回数据
  42. * @return array
  43. */
  44. private static function getResult($apiName, $result, $format){
  45. switch ($apiName){
  46. case 'pconline': // 太平洋
  47. $address = [];
  48. if(isset($result['pro'])){
  49. $address[] = isset($result['pro'])? $result['pro'] : '';
  50. }
  51. if(isset($result['city'])){
  52. $address[] = isset($result['city'])? $result['city'] : '';
  53. }
  54. return $format==1 && $address? implode(' ', $address) : $result;
  55. break;
  56. case 'taobao': // 淘宝
  57. $address = [];
  58. $result = isset($result['data'])? $result['data'] : [];
  59. if(isset($result['region'])){
  60. $address[] = isset($result['region'])? $result['region'] : '';
  61. }
  62. if(isset($result['city'])){
  63. $address[] = isset($result['city'])? $result['city'] : '';
  64. }
  65. return $format==1 && $address? implode(' ', $address) : $result;
  66. break;
  67. default: // 默认
  68. return $format==1? (isset($result['city'])? $result['city'] : '') : $result;
  69. }
  70. }
  71. }