IpTools   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
c 0
b 0
f 0
lcom 0
cbo 0
dl 0
loc 42
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getClientIp() 0 26 6
A validateIp() 0 8 2
1
<?php
2
3
namespace Hongliang\Defender\Utility;
4
5
class IpTools
6
{
7
    public static function getClientIp()
0 ignored issues
show
Coding Style introduced by
getClientIp uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
8
    {
9
        $ip_keys = [
10
            'HTTP_CLIENT_IP',
11
            'REMOTE_ADDR',
12
            'HTTP_X_FORWARDED_FOR',
13
            'HTTP_X_FORWARDED',
14
            'HTTP_X_CLUSTER_CLIENT_IP',
15
            'HTTP_FORWARDED_FOR',
16
            'HTTP_FORWARDED',
17
        ];
18
        foreach ($ip_keys as $key) {
19
            if (array_key_exists($key, $_SERVER) === true) {
20
                foreach (explode(',', $_SERVER[$key]) as $ip) {
21
                    // trim for safety measures
22
                    $ip = trim($ip);
23
                    // attempt to validate IP
24
                    if (self::validateIp($ip)) {
25
                        return $ip;
26
                    }
27
                }
28
            }
29
        }
30
31
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
32
    }
33
34
    /**
35
     * Ensures an ip address is both a valid IP and does not fall within
36
     * a private network range.
37
     */
38
    public static function validateIp($ip)
39
    {
40
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
41
            return false;
42
        }
43
44
        return true;
45
    }
46
}
47