xref: /web-php/include/ip-to-country.inc (revision 7023ed38)
1<?php
2// Returns the real IP address of the user
3function i2c_realip()
4{
5    // No IP found (will be overwritten by for
6    // if any IP is found behind a firewall)
7    $ip = false;
8
9    // If HTTP_CLIENT_IP is set, then give it priority
10    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
11        $ip = $_SERVER["HTTP_CLIENT_IP"];
12    }
13
14    // User is behind a proxy and check that we discard RFC1918 IP addresses
15    // if they are behind a proxy then only figure out which IP belongs to the
16    // user.  Might not need any more hackin if there is a squid reverse proxy
17    // infront of apache.
18    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
19
20        // Put the IP's into an array which we shall work with shortly.
21        $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
22        if ($ip) { array_unshift($ips, $ip); $ip = false; }
23
24        for ($i = 0; $i < count($ips); $i++) {
25            // Skip RFC 1918 IP's 10.0.0.0/8, 172.16.0.0/12 and
26            // 192.168.0.0/16
27            // Also skip RFC 6598 IP's
28            if (!preg_match('/^(?:10|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])|172\.(?:1[6-9]|2\d|3[01])|192\.168)\./', $ips[$i]) && ip2long($ips[$i])) {
29                $ip = $ips[$i];
30                break;
31            }
32        }
33    }
34
35    // Return with the found IP or the remote address
36    return $ip ?: $_SERVER['REMOTE_ADDR'];
37}
38