1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
function get_ip() { $ip = '未知IP'; if (!empty(filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP'))) { return is_ip(filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP')) ? filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP') : $ip; } elseif (!empty(filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR'))) { return is_ip(filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR')) ? filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR') : $ip; } else { return is_ip(filter_input(INPUT_SERVER, 'REMOTE_ADDR')) ? filter_input(INPUT_SERVER, 'REMOTE_ADDR') : $ip; } }
function is_ip($str) { $ip = explode('.', $str); for ($i = 0; $i < count($ip); $i++) { if ($ip[$i] > 255) { return false; } } return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $str); }
public function checkIp($ip): bool { $pattern = '/(^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.\*$)|(^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.\*$)|(^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.\*$)|(\*)/'; if (preg_match($pattern, $ip) || filter_var($ip, FILTER_VALIDATE_IP)) { return true; } return false; }
|