Reputation: 2349
(1.) I want allow visitors to access a page just from a some IP Address Range (paragraph 2). easily as adding more regex of IP Address to IP Address List.
My regular expression array is :
$IP_LIST_ACCESS = array(
"/^188\.133\.11\.([1-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-4]))$/"
,"/^188\.133\.14\.([1-9]|[1-9][0-9]|1([0-1][0-9]|2[0-8]))$/"
,"/^127\.0\.0\.1$/"
);
(2.) IP Range of above array is 188.133.11.1-188.133.11.254
and 188.136.14.1-188.136.14.128
and 127.0.0.1
and bellow is My codes to detect wrong ip address and die:
$USER_IP_ADDR = $_SERVER['REMOTE_ADDR'];
foreach ($IP_LIST_ACCESS as $IP_ACC_ARRAY)
{
if (!preg_match($IP_ACC_ARRAY, $USER_IP_ADDR))
{
echo '#INVALID IP'; #DEBUG
die;
}
}
(3.) with my above codes , always give INVALID IP
Error (always detect as wrong IP address) .
Where is the problem ?
EDIT
(4.) I just want to do this , not exact with preg_match if have a better way .
Upvotes: 0
Views: 1747
Reputation: 1526
Better use ip2long insted of regex, its easyer to read and has better performance.
$ip_ranges = array(
array(
'from' => ip2long('188.133.11.1'),
'to' => ip2long('188.133.11.254')
),
array(
'from' => ip2long('188.136.14.1'),
'to' => ip2long('188.136.14.128')
),
array(
'from' => ip2long('127.0.0.0'),
'to' => ip2long('127.255.255.255')
),
);
$USER_IP_ADDR = $_SERVER['REMOTE_ADDR'];
$USER_IP_ADDR_LONG = ip2long($USER_IP_ADDR);
$USER_IS_PERMITTED = false;
foreach ($ip_ranges as $ip_range) {
if ($ip_range['from'] <= $USER_IP_ADDR_LONG && $ip_range['to'] >= $USER_IP_ADDR_LONG) {
$USER_IS_PERMITTED = true;
}
}
if (!$USER_IS_PERMITTED) {
echo '#INVALID IP: ' . $USER_IP_ADDR; #DEBUG
die;
}
Upvotes: 3
Reputation: 705
I'm fairly certain you want if (preg_match($IP_ACC_ARRAY, $USER_IP_ADDR) === 1)
. Right now you're displaying the error if it doesn't match. This is the quickest solution, but perhaps the ip2long
-based solutions proposed in other answers is the most correct.
Upvotes: 0
Reputation: 4114
Take a look at ip2long()
, it generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.
Later, you can perform range operations on it.
Upvotes: 1