至尊技术网 - 访客ip
type: channel
link: https://www.zzwws.cn/tag/%E8%AE%BF%E5%AE%A2ip/
items: PHP获取访客、本地ip

PHP获取访客、本地ip
type: item
date: 2020-11-15T11:27:00+08:00
description: 第一种（使用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",…