在開發網站的時候很多時候都要使用到訪客的ip統計來分析一些數據,吾愛編程為大家分享一個PHP獲取訪客IP代碼,可以記錄訪客的ip 等一些信息,閒話就不說了直接上代碼:
class get_gust_info { ////獲得訪客浏覽器類型 function GetBrowser(){ if(!empty($_SERVER['HTTP_USER_AGENT'])){ $br = $_SERVER['HTTP_USER_AGENT']; if (preg_match('/MSIE/i',$br)) { $br = 'MSIE'; }elseif (preg_match('/Firefox/i',$br)) { $br = 'Firefox'; }elseif (preg_match('/Chrome/i',$br)) { $br = 'Chrome'; }elseif (preg_match('/Safari/i',$br)) { $br = 'Safari'; }elseif (preg_match('/Opera/i',$br)) { $br = 'Opera'; }else { $br = 'Other'; } return $br; }else{return "獲取浏覽器信息失敗!";} } ////獲得訪客浏覽器語言 function GetLang(){ if(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])){ $lang = $_SERVER['HTTP_ACCEPT_LANGUAGE']; $lang = substr($lang,0,5); if(preg_match("/zh-cn/i",$lang)){ $lang = "簡體中文"; }elseif(preg_match("/zh/i",$lang)){ $lang = "繁體中文"; }else{ $lang = "English"; } return $lang; }else{return "獲取浏覽器語言失敗!";} } ////獲取訪客操作系統 function GetOs(){ if(!empty($_SERVER['HTTP_USER_AGENT'])){ $OS = $_SERVER['HTTP_USER_AGENT']; if (preg_match('/win/i',$OS)) { $OS = 'Windows'; }elseif (preg_match('/mac/i',$OS)) { $OS = 'MAC'; }elseif (preg_match('/linux/i',$OS)) { $OS = 'Linux'; }elseif (preg_match('/unix/i',$OS)) { $OS = 'Unix'; }elseif (preg_match('/bsd/i',$OS)) { $OS = 'BSD'; }else { $OS = 'Other'; } return $OS; }else{return "獲取訪客操作系統信息失敗!";} } ////獲得訪客真實ip function Getip(){ if(!empty($_SERVER["HTTP_CLIENT_IP"])){ $ip = $_SERVER["HTTP_CLIENT_IP"]; } if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ //獲取代理ip $ips = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']); } if($ip){ $ips = array_unshift($ips,$ip); } $count = count($ips); for($i=0;$i<$count;$i++){ if(!preg_match("/^(10|172\.16|192\.168)\./i",$ips[$i])){//排除局域網ip $ip = $ips[$i]; break; } } $tip = $ip ? $ip : $_SERVER['REMOTE_ADDR']; if($tip=="127.0.0.1"){ //獲得本地真實IP return $this->get_onlineip(); }else{ return $tip; } } ////獲得本地真實IP function get_onlineip() { $mip = file_get_contents("http://www.ip138.com/ip2city.asp"); if($mip){ preg_match("/\[.*\]/",$mip,$sip); $p = array("/\[/","/\]/"); return preg_replace($p,"",$sip[0]); }else{return "獲取本地IP失敗!";} } ////根據ip獲得訪客所在地地名 function Getaddress($ip=''){ if(empty($ip)){ $ip = $this->Getip(); } //根據新浪api接口獲取 $ipadd = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=".$ip); if($ipadd){ $charset = iconv("gbk","utf-8",$ipadd); preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$charset,$ipadds); return $ipadds; //返回一個二維數組 }else{return "addree is none";} } } $gifo = new get_gust_info(); echo "你的ip:".$gifo->Getip(); echo " 所在地:"; print_r($gifo->Getaddress()); echo " 浏覽器類型:".$gifo->GetBrowser(); echo " 浏覽器語言:".$gifo->GetLang(); echo " 操作系統:".$gifo->GetOs();*