php根據ip擷取地區的程式碼

來源:互聯網
上載者:User

   先用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;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;歡迎來自&nbsp;<b>".$ipp[1]."</b>&nbsp;的朋友!</div>";

}

echo lazdf(GetIP());//輸出ip

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.