Total Complexity | 10 |
Total Lines | 67 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
5 | class IPValidator |
||
6 | { |
||
7 | /** |
||
8 | * Fetch users IP-address |
||
9 | * |
||
10 | * @param array $server $_SERVER-array or any array with |
||
11 | * |
||
12 | * @return string $userIP User IP-address |
||
13 | */ |
||
14 | 10 | public function getUserIP($server) |
|
15 | { |
||
16 | 10 | if (!empty($server['HTTP_CLIENT_IP'])) { |
|
17 | 1 | $userIP = $server['HTTP_CLIENT_IP']; |
|
18 | 9 | } elseif (!empty($server['HTTP_X_FORWARDED_FOR'])) { |
|
19 | 1 | $userIP = $server['HTTP_X_FORWARDED_FOR']; |
|
20 | } else { |
||
21 | 8 | $userIP = $server['REMOTE_ADDR']; |
|
22 | } |
||
23 | 10 | return $userIP; |
|
24 | } |
||
25 | |||
26 | |||
27 | /** |
||
28 | * Use regular expression to check if input matches ip4 or ip6 syntax |
||
29 | * |
||
30 | * @param string |
||
31 | * |
||
32 | * @return string |
||
33 | */ |
||
34 | 25 | public function pregMatchIP($ipToValidate) |
|
35 | { |
||
36 | 25 | $ip4regex = "((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$))"; |
|
37 | 25 | $ip6regex = "((^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))"; |
|
38 | |||
39 | // Check if $ip matches ip4 syntax |
||
40 | 25 | if (preg_match($ip4regex, $ipToValidate)) { |
|
41 | 7 | return "ip4"; |
|
42 | } |
||
43 | |||
44 | // Check if $ip matches ip6 syntax |
||
45 | 18 | if (preg_match($ip6regex, $ipToValidate)) { |
|
46 | 6 | return "ip6"; |
|
47 | } |
||
48 | |||
49 | 12 | return ""; |
|
50 | } |
||
51 | |||
52 | |||
53 | /** |
||
54 | * Check if incomping IP-address is valid |
||
55 | * |
||
56 | * @param string |
||
57 | * |
||
58 | * @return array |
||
59 | */ |
||
60 | 16 | public function validateIP($ipToValidate) |
|
72 | ]; |
||
73 | } |
||
74 | } |
||
75 |