先用php擷取原生ip,再用php的curl函數來擷取使用者的詳細地區.下面來看一下代碼;
| 代碼如下 |
|
| /* * 這個函數是擷取用戶端和IP */ function GetIP() { if(!empty($_SERVER["HTTP_CLIENT_IP"])) { $cip = $_SERVER["HTTP_CLIENT_IP"]; } else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) { $cip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if(!empty($_SERVER["REMOTE_ADDR"])) { $cip = $_SERVER["REMOTE_ADDR"]; } else { $cip = ''; } preg_match("/[d.]{7,15}/", $cip, $cips); $cip = isset($cips[0]) ? $cips[0] : 'unknown'; unset($cips); return $cip; } |
方法一,利用QQWry.Dat IP庫,我們只胖乎乎
用簡單的辦法。
使用樣本
樣本一:
| 代碼如下 |
|
| $IpLocation = new IpLocation(); $client = $IpLocation->getlocation(); print_r($client); |
樣本二:
| 代碼如下 |
|
| $IpLocation = new IpLocation('../qqwry/QQWry.Dat'); $client = $IpLocation->getlocation('115.148.101.72'); print_r($client); |
具體的IP庫與Iplocation類檔案這裡不介紹了大家百度搜尋吧。
方法二,利用api介面
樣本一,
| 代碼如下 |
|
| /** * 擷取IP地區 * Enter description here ... * @param unknown_type $ip */ function GetArea($ip){ $url = "http://ip168.com/ip/?ip=".$ip; $contents = file_get_contents($url); // preg_match_all('/<h3[sS]*?(<a[sS]*?</h3>)/',$contents,$rs); preg_match_all('|<div>本站主要資料:.*</div>|',$contents,$rsR); $rsR[0][0] = str_replace("<div>本站主要資料:", "", $rsR[0][0]); $rsR[0][0] = str_replace("</div>", "", $rsR[0][0]); return $rsR[0][0]; } |
樣本二,
下面這個函數是用php的curl函數從網路上擷取詳細地區
| 代碼如下 |
|
| function lazdf($ip){ $curl= curl_init(); curl_setopt($curl,CURLOPT_URL,"http://www.ip138.com/ips138.asp?ip=".$ip); curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); $ipdz=curl_exec($curl); curl_close($curl); preg_match("/<ul class="ul1"><li>(.*?)</li>/i",$ipdz,$jgarray); preg_match("/本 www.111cn.net 站主要資料:(.*)/i", $jgarray[1],$ipp); return "<div class="global_widht global_zj zj" style="background: none repeat scroll 0% 0% rgb(226, 255, 191); font-size: 12px; color: rgb(85, 85, 85); height: 30px; line-height: 30px; border-bottom: 1px solid rgb(204, 204, 204); text-align: left;"> 歡迎來自 <b>".$ipp[1]."</b> 的朋友!</div>"; } echo lazdf(GetIP());//輸出ip |