在php中获取IP地址的方法有很多种,下面我介绍利用linux命令获取IP地址然后转换成数组输出,下面也介绍了一些常用关于php ip地址处理实例.
PHP获取服务器IP地址,用PHP执行ifconfig获得Linux服务器IP并输出为数组,下面是代码:
- <?php
- function getServerIp(){
- $ss = exec('/sbin/ifconfig | sed -n 's/^ *.*addr:\([0-9.]\{7,\}\) .*$/\1/p'',$arr);
- return $arr;
- }
- $ips=getServerIp();
-
- foreach($ips as $k=>$v){
- if(substr($v,0,3)=='127' || substr($v,0,3)=='10.' || substr($v,0,7)=='192.168' || substr($v,0,6)=='172.16'){
- unset($ips[$k]);
- }
- }
- shuffle($ips);
- print_r($ips);
- ?>
一些php获取ip地址例,代码如下:
- <?php
- function GetIP(){
- if(!emptyempty($_SERVER["HTTP_CLIENT_IP"])){
- $cip = $_SERVER["HTTP_CLIENT_IP"];
- }
- elseif(!emptyempty($_SERVER["HTTP_X_FORWARDED_FOR"])){
- $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
- }
- elseif(!emptyempty($_SERVER["REMOTE_ADDR"])){
- $cip = $_SERVER["REMOTE_ADDR"];
- }
- else{
- $cip = "无法获取!";
- }
- return $cip;
- }
- echo GetIP();
- ?>
我这里有一个比较公用的方法来获取用户ip地址,代码如下:
- function get_user_ip() {
- if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP']!='unknown') {
- $ip = $_SERVER['HTTP_CLIENT_IP'];
- } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']!='unknown') {
- $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
- } else {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- return $ip;
- }
PHP获取IP所在地区(调用新浪API获取IP所在地),代码如下:
- function get_location($ip){
- $curl = curl_init();
- curl_setopt($curl,CURLOPT_URL, "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip);
- $location = curl_exec($curl);
- $location = json_decode($location);
- if($location===FALSE) return "";
- return emptyempty($location->desc) ? $location->province.$location->city.$location->district.$location->isp : $location->desc;
- }
|