Laravel使用淘宝IP库和新浪IP库获取客户端的地理位置(第二次修改)

 1 /**淘宝地址库解析*/
 2 function getTaoBao($clientIp = '')
 3 {
 4     $result = [];
 5     $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $clientIp;
 6 
 7     try {
 8         $ch = curl_init();
 9         $timeout = 5;
10         curl_setopt($ch, CURLOPT_URL, $url);
11         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
12         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
13         $file_contents = curl_exec($ch);
14         curl_close($ch);
15 
16         if (!$file_contents) return $result;
17         $data = json_decode($file_contents)->data;
18 
19         if (!$data) return $result;
20         $result['country'] = isset($data->area) ? $data->area : '';
21         $result['province'] = isset($data->region) ? $data->region : '';
22         $result['city'] = isset($data->city) ? $data->city : '';
23         $result['isp'] = isset($data->isp) ? $data->isp : '';
24 
25         return $result;
26     } catch (Exception $e) {
27         return $result;
28     }
29 }
30 
31 /**新浪地址库解析*/
32 function getSina($clientIp = '')
33 {
34     $result = [];
35     $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" . $clientIp;
36     try {
37         $ch = curl_init();
38         $timeout = 5;
39         curl_setopt($ch, CURLOPT_URL, $url);
40         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
41         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
42         $file_contents = curl_exec($ch);
43         curl_close($ch);
44 
45         if (!$file_contents) return $result;
46         $data = json_decode($file_contents);
47 
48         if (!$data) return $result;
49         $result['country'] = isset($data->country) ? $data->country : '';
50         $result['province'] = isset($data->province) ? $data->province : '';
51         $result['city'] = isset($data->city) ? $data->city : '';
52         $result['isp'] = isset($data->isp) ? $data->isp : '';
53 
54         return $result;
55     } catch (Exception $e) {
56         return $result;
57     }
58 }
59 
60 /**获取客户端的IP地理位置*/
61 function getMemberPosition($clinetIp = '')
62 {
63     if (!$clinetIp || $clinetIp == '::1') {
64         return '';
65     }
66     try {
67         $data = getTaoBao($clinetIp);
68         if (!$data) $data = getSina($clinetIp);
69     } catch (Exception $e) {
70         $data = getSina($clinetIp);
71     }
72     if (!$data) {
73         return '';
74     }
75     if ($data['province'] && $data['city']) {
76         if ($data['province'] == $data['city'])
77             return $data['province'];
78         return $data['province'] . $data['city'];
79     } else {
80         return !$data['province'] ? ($data['city'] ? $data['city'] : '火星上') : '火星上';
81     }
82 }

 

posted @ 2017-09-29 09:20  流浪在阿尔卑斯的野狼  阅读(230)  评论(0编辑  收藏  举报