11 08 2015

4. 检测用户位置

使用下面的函数,可以检测用户是在哪个城市访问你的网站

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function detect_city($ip) {
         
        $default 'UNKNOWN';
  
        $curlopt_useragent 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
         
        $url 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();
         
        $curl_opt array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' $_SERVER['HTTP_HOST'],
        );
         
        curl_setopt_array($ch$curl_opt);
         
        $content = curl_exec($ch);
         
        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }
         
        curl_close($ch);
         
        if ( preg_match('{<li>City : ([^<]*)</li>}i'$content$regs) )  {
            $city $regs[1];
        }
        if ( preg_match('{<li>State/Province : ([^<]*)</li>}i'$content$regs) )  {
            $state $regs[1];
        }
  
        if$city!='' && $state!='' ){
          $location $city ', ' $state;
          return $location;
        }else{
          return $default
        }
         
    }

语法:

?
1
2
3
4
5
<?php
$ip $_SERVER['REMOTE_ADDR'];
$city = detect_city($ip);
echo $city;
?>
发表评论