Jump to content

Allow IP and Ban the rest...


sammo_ti

Recommended Posts

Hi, I'm a little stuck... I've been working on a code to ban all IP's except '150.208.193.*' range and '179.155.3.2'.

I've gotten it to ban all IP's so far...  Any help will be appreciated or better ways of doing it...

 

Thanks in advanced...

 

 

<?php


//$valid_ips[] = '150.208.193.*';
//$valid_ips[] = '179.155.3.2';

$banned_ip[] = '*.*.*.*'; 

function is_banned($ip)
{ $pattern = str_replace(array('*', '.'), array('\d+', '\.'), $ip);
return preg_match("~^{$pattern}$~", $_SERVER['REMOTE_ADDR']);
}
if (array_filter($banned_ip, 'is_banned'))
{ 
echo 'Banned';
exit();
}
else
{ 
echo 'Not banned';
exit();
}

Link to comment
https://forums.phpfreaks.com/topic/95922-allow-ip-and-ban-the-rest/
Share on other sites

Try this:

<?php
$banned_ips = array(
    '150.208.193.*',
    '179.155.3.2',
);

$user_ip = $_SERVER['REMOTE_ADDR'];
$is_allowed = false;
foreach ($banned_ips as $ip) {
    $octets     = explode('.', $ip);
    $num_octets = count($octets);
    if($num_octets > 4) continue; // malformed IP address
    
    $ip .= str_repeat('.*', 4 - $num_octets);
    $ip  = str_replace('*', '[0-9]{1,3}', $ip);
    
    if (preg_match('#^' . $ip . '$#', $user_ip)) {
        $is_allowed = true;
        break; // no need to check the remaining addresses
    }
}

if (!$is_allowed) {
    die('Sorry, you are not allowed to view this page.');
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.