UtilsTool.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare (strict_types = 1);
  3. namespace library\utils;
  4. // +----------------------------------------------------------------------
  5. // | [ 工具类-常用操作 ]
  6. // +----------------------------------------------------------------------
  7. // | Copyright (c) 2018-2020 rights reserved.
  8. // +----------------------------------------------------------------------
  9. // | Author: TABLE ME
  10. // +----------------------------------------------------------------------
  11. // | Date: 2020-08-29 20:41
  12. // +----------------------------------------------------------------------
  13. use library\utils\Http;
  14. class UtilsTool
  15. {
  16. /**
  17. * ip地址转区域
  18. * @param type $ip
  19. */
  20. static public function ipToArea($ip=''){
  21. $timeout = 60;
  22. $http_header = array(
  23. 'content-type:application/json;charset=utf8'
  24. );
  25. $ip=urlencode($ip);
  26. $url = "http://ip.ws.126.net/ipquery?ip={$ip}";
  27. $ch = curl_init();
  28. curl_setopt($ch, CURLOPT_URL, $url);
  29. curl_setopt($ch, CURLOPT_HEADER, false);
  30. curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header);
  31. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
  32. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  33. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  34. $result = curl_exec($ch);
  35. curl_close($ch);
  36. if(!mb_check_encoding($result, "utf-8")){
  37. $result = mb_convert_encoding($result,'UTF-8',['ASCII','UTF-8','GB2312','GBK']);
  38. }
  39. if(!empty($result)){
  40. $result = trim($result);
  41. if(empty($result)){
  42. return false;
  43. }
  44. $result = explode("localAddress=", $result);
  45. if(empty($result) || count($result)<2){
  46. return false;
  47. }
  48. $jsonStr = $result[1];
  49. $jsonStr = str_replace("city", '"city"', $jsonStr);
  50. $jsonStr = str_replace("province", '"province"', $jsonStr);
  51. $jsonStr = str_replace(" ", "", $jsonStr);
  52. if(empty($jsonStr)){
  53. return false;
  54. }
  55. return @json_decode($jsonStr,true);
  56. }else{
  57. return false;
  58. }
  59. }
  60. }