Below you can find a simple php script that blocks ip addresses. It uses a function (called iplong) that converts the standard IPv4 address to a long int value and the main function (ban) that checks if a provided ip can be found in a list of blocked addresses. Hope you will find this useful.
1 | function ban( $range = array (), $ip = '' ) |
2 | { |
3 | $ip = longip(trim( $ip )); |
4 | if ( $ip == FALSE) |
5 | { |
6 | return FALSE; |
7 | } |
8 | if ( empty ( $ip )) |
9 | { |
10 | return FALSE; |
11 | } |
12 | foreach ( $range AS $key => $val ) |
13 | { |
14 | $temp = explode ( '-' , $val ); |
15 | if ( empty ( $temp [0])) |
16 | { |
17 | return FALSE; |
18 | } |
19 | else |
20 | { |
21 | $start_ip = longip(trim( $temp [0])); |
22 | if ( $start_ip == FALSE) |
23 | { |
24 | return FALSE; |
25 | } |
26 | } |
27 | if ( empty ( $temp [1])) |
28 | { |
29 | if ( $ip == $start_ip ) |
30 | { |
31 | return TRUE; |
32 | } |
33 | } |
34 | else |
35 | { |
36 | $stop_ip = longip(trim( $temp [1])); |
37 | if ( $stop_ip == FALSE) |
38 | { |
39 | return FALSE; |
40 | } |
41 | } |
42 | if ( $start_ip <= $ip && $ip <= $stop_ip ) |
43 | { |
44 | return TRUE; |
45 | } |
46 | } |
47 | return FALSE; |
48 | } |
49 | function longip( $ip ) |
50 | { |
51 | if ( empty ( $ip )) |
52 | { |
53 | return FALSE; |
54 | } |
55 | $block = explode ( '.' , $ip ); |
56 | if ( count ( $block ) != 4) |
57 | { |
58 | return FALSE; |
59 | } |
60 | $i = 3; |
61 | $block_ip = 0; |
62 | foreach ( $block as $k => $v ) |
63 | { |
64 | $v = filter_var( $v , FILTER_VALIDATE_INT); |
65 | if ( $v < 0) |
66 | { |
67 | $v = 0; |
68 | } |
69 | if ( $v > 255) |
70 | { |
71 | $v = 255; |
72 | } |
73 | $block_ip += pow(256, $i )* $v ; |
74 | $i --; |
75 | } |
76 | return $block_ip ; |
77 | } |
78 |
79 | //usage |
80 | $block_range = array ( '192.168.1.0 - 192.168.2.255' , |
81 | '192.168.4.0 - 192.168.4.255' , |
82 | '192.168.6.1' |
83 | ); |
84 |
85 | $ip = '192.168.3.255' ; |
86 |
87 | if (ban( $block_range , '192.168.6.1' )) |
88 | { |
89 | echo "BAN\n" ; |
90 | } |
91 | else |
92 | { |
93 | echo "UNBAN\n" ; |
94 | } |