|
1 | 1 | <?php |
2 | 2 |
|
3 | 3 | /** |
4 | | - * @return string |
| 4 | + * Normalize and validate an IP address candidate from a request header. |
| 5 | + * |
| 6 | + * Trims whitespace, takes the first comma-separated token (for XFF-like |
| 7 | + * headers that may contain a chain of addresses), and validates the result |
| 8 | + * with filter_var(). |
| 9 | + * |
| 10 | + * @param string $raw Raw header value. |
| 11 | + * @param int $extraFlags Additional FILTER_FLAG_* flags (e.g. FILTER_FLAG_IPV6). |
| 12 | + * |
| 13 | + * @return string|false The validated IP string, or false on failure. |
5 | 14 | */ |
6 | | -function getClientIp() { |
7 | | - if (!empty($_SERVER['HTTP_CLIENT_IP'])) { |
8 | | - $ip = $_SERVER['HTTP_CLIENT_IP']; |
9 | | - } elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) { |
10 | | - $ip = $_SERVER['HTTP_X_REAL_IP']; |
11 | | - } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { |
12 | | - $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; |
13 | | - $ip = preg_replace('/,.*/', '', $ip); # hosts are comma-separated, client is first |
14 | | - } else { |
15 | | - $ip = $_SERVER['REMOTE_ADDR']; |
| 15 | +function normalizeCandidateIp($raw, $extraFlags = 0) |
| 16 | +{ |
| 17 | + $ip = trim($raw); |
| 18 | + // For XFF-like values, take the first address before a comma. |
| 19 | + if (($pos = strpos($ip, ',')) !== false) { |
| 20 | + $ip = trim(substr($ip, 0, $pos)); |
| 21 | + } |
| 22 | + if ($ip === '') { |
| 23 | + return false; |
16 | 24 | } |
| 25 | + return filter_var($ip, FILTER_VALIDATE_IP, $extraFlags); |
| 26 | +} |
17 | 27 |
|
18 | | - return preg_replace('/^::ffff:/', '', $ip); |
| 28 | +/** |
| 29 | + * @return string |
| 30 | + */ |
| 31 | +function getClientIp() |
| 32 | +{ |
| 33 | + // Cloudflare IPv6 header — must be a valid IPv6 address. |
| 34 | + if (!empty($_SERVER['HTTP_CF_CONNECTING_IPV6'])) { |
| 35 | + $ip = normalizeCandidateIp($_SERVER['HTTP_CF_CONNECTING_IPV6'], FILTER_FLAG_IPV6); |
| 36 | + if ($ip !== false) { |
| 37 | + return preg_replace('/^::ffff:/', '', $ip); |
| 38 | + } |
| 39 | + } |
| 40 | + // Other forwarding / proxy headers — accept any valid IP. |
| 41 | + foreach (['HTTP_CLIENT_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR'] as $header) { |
| 42 | + if (!empty($_SERVER[$header])) { |
| 43 | + $ip = normalizeCandidateIp($_SERVER[$header]); |
| 44 | + if ($ip !== false) { |
| 45 | + return preg_replace('/^::ffff:/', '', $ip); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + // Fallback: REMOTE_ADDR is set by the web server and is always a single IP. |
| 50 | + $ip = normalizeCandidateIp($_SERVER['REMOTE_ADDR'] ?? ''); |
| 51 | + if ($ip !== false) { |
| 52 | + return preg_replace('/^::ffff:/', '', $ip); |
| 53 | + } |
| 54 | + return $_SERVER['REMOTE_ADDR'] ?? ''; |
19 | 55 | } |
0 commit comments