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
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.');
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.