根據(jù)IP地址來獲取用戶所在的地區(qū),這個(gè)需要借助一個(gè)外部api或一個(gè)數(shù)據(jù)庫(kù)來記錄IP地址是哪里的,下面我總結(jié)一些常用的方法給各位參考,先用php獲取本機(jī)的ip,再用php的curl函數(shù)來獲取用戶的詳細(xì)地區(qū),下面來看一下代碼:
- /*
- * 這個(gè)函數(shù)是獲取客戶端和IP
- */
- function GetIP()
- {
- if(!emptyempty($_SERVER["HTTP_CLIENT_IP"]))
- {
- $cip = $_SERVER["HTTP_CLIENT_IP"];
- }
- else if(!emptyempty($_SERVER["HTTP_X_FORWARDED_FOR"]))
- {
- $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
- }
- else if(!emptyempty($_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庫(kù),用簡(jiǎn)單的辦法,使用示例如下:
- $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庫(kù)與Iplocation類文件這里不介紹了大家百度搜索吧。
方法二,利用api接口
示例一,代碼如下:
- /**
- * 獲取IP地區(qū)
- * 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>本站主數(shù)據(jù):.*</div>|',$contents,$rsR);
- $rsR[0][0] = str_replace("<div>本站主數(shù)據(jù):", "", $rsR[0][0]);
- $rsR[0][0] = str_replace("</div>", "", $rsR[0][0]);
- return $rsR[0][0];
- }
示例二,下面這個(gè)函數(shù)是用php的curl函數(shù)從網(wǎng)路上獲取詳細(xì)地區(qū),代碼如下:
- 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("/本站主數(shù)據(jù):(.*)/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());//輸出Vevb.comip
新聞熱點(diǎn)
疑難解答