预定义变量$_SERVER的用法中,我们可以发现参数 ‘REMOTE_ADDR‘的作用是:浏览当前页面的用户的 IP 地址。
根据这个我们可以获取客户端的IP,根据获取的IP我们又可以进一步获取对方的所在地等其他信息。
这一节主要是了解一下如何获取客户端的IP地址,并定位其所在地。我们先看看代码实现:
<?php header('Content-Type:text/html;Charset=utf-8'); function GetIp(){ $realip = ''; $unknown = 'unknown'; if (isset($_SERVER)){ if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){ $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach($arr as $ip){ $ip = trim($ip); if ($ip != 'unknown'){ $realip = $ip; break; } } }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){ $realip = $_SERVER['HTTP_CLIENT_IP']; }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){ $realip = $_SERVER['REMOTE_ADDR']; }else{ $realip = $unknown; } }else{ if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){ $realip = getenv("HTTP_X_FORWARDED_FOR"); }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){ $realip = getenv("HTTP_CLIENT_IP"); }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){ $realip = getenv("REMOTE_ADDR"); }else{ $realip = $unknown; } } $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown; return $realip; } function GetIpLookup($ip = ''){ if(empty($ip)){ $ip = GetIp(); } $address = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip); if(empty($address)){ return false; } $jsonMatches = array(); preg_match('#\{.+?\}#', $address, $jsonMatches); if(!isset($jsonMatches[0])){ return false; } $address_json = json_decode($jsonMatches[0], true); if(isset($address_json['ret']) && $address_json['ret'] == 1){ $address_json['ip'] = $ip; unset($address_json['ret']); }else{ return false; } return $address_json; } $ipInfos = GetIpLookup(); var_dump($ipInfos); echo "<br>"; echo "你的地址: " .$ipInfos ["country"].$ipInfos ["province"].$ipInfos ["city"]. "<br>";
将代码部署到SAE,运行结果如下:
从运行结果中可以看到 $address_json 中包含的内容是:
array(10) { ["start"]=> int(-1) ["end"]=> int(-1) ["country"]=> string(6) "中国" ["province"]=> string(6) "四川" ["city"]=> string(6) "成都" ["district"]=> string(0) "" ["isp"]=> string(0) "" ["type"]=> string(0) "" ["desc"]=> string(0) "" ["ip"]=> string(13) "121.48.152.31"
}
我们只要从其中提取出需要的信息显示出来即可。
本次获取用户所在地使用了新浪提供的API,也可以根据实际情况采用其他API来实现。根据IP还能获取所在地天气,交通等各种信息,有兴趣大家可以再一起讨论了。
时间: 2024-10-11 03:09:08