第一种（使用CDN可正常获取访客ip）：function get_real_ip() { static $realip = NULL; if ($realip !== NULL) { return $realip; } if (isset($_SERVER)) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach ($arr as $ip) { $ip = trim($ip); if ($ip != 'unknown') { $realip = $ip; break; } } } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $realip = $_SERVER['HTTP_CLIENT_IP']; } else { if (isset($_SERVER['REMOTE_ADDR'])) { $realip = $_SERVER['REMOTE_ADDR']; } else { $realip = '0.0.0.0'; } } } else { if (getenv('HTTP_X_FORWARDED_FOR')) { $realip = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('HTTP_CLIENT_IP')) { $realip = getenv('HTTP_CLIENT_IP'); } else { $realip = getenv('REMOTE_ADDR'); } } preg_match("/[\d\.]{7,15}/", $realip, $onlineip); $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0'; return $realip; } echo get_real_ip(); 第二种：function get_real_ip() { static $realip = NULL; if ($realip !== NULL) { return $realip; } if(getenv('REMOTE_ADDR')) { $realip = getenv('REMOTE_ADDR'); }else if(getenv('HTTP_CLIENT_IP')) { $realip = getenv('HTTP_CLIENT_IP'); }else if(getenv('HTTP_X_FROWARD_FOR')) { $realip = getenv('HTTP_X_FROWARD_FOR'); } return $realip; } echo get_real_ip(); 第三种：function get_real_ip() { static $realip = NULL; if ($realip !== NULL) { return $realip; } $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if (filter_var($client, FILTER_VALIDATE_IP)) { $realip = $client; } else if (filter_var($forward, FILTER_VALIDATE_IP)) { $realip = $forward; } else { $realip = $remote; } return $realip; } echo get_user_ip(); 把IPV4地址转化成int型$ip = sprintf('%u', ip2long(get_real_ip())); echo $ip; 把int型转化成IPV4地址echo long2ip('2130706433');//127.0.0.1 生成随机ipfunction rand_ip(){ $ip2id= round(rand(600000, 2550000) / 10000); $ip3id= round(rand(600000, 2550000) / 10000); $ip4id= round(rand(600000, 2550000) / 10000); //下面是第二种方法，在以下数据中随机抽取 $arr_1 = array("218","218","66","66","218","218","60","60","202","204","66","66","66","59","61","60","222","221","66","59","60","6066","218","218","62","63","64","66","66","122","211"); $randarr= mt_rand(0,count($arr_1)-1); $ip1id = $arr_1[$randarr]; return $ip1id.".".$ip2id.".".$ip3id.".".$ip4id; } echo rand_ip();