Search code examples
phpip

Ban IP Ranges php


I found this code:

<?php               
    $ban_ip_range = array('10.49.*.*');
    $user_ip = $_SERVER['REMOTE_ADDR'];

    if(!empty($ban_ip_range)) {
        foreach($ban_ip_range as $range) {
            $range = str_replace('*','(.*)', $range);

            if(preg_match('/'.$range.'/', $user_ip)) {
                echo "NO access";
            }
            else {
                echo 'you have access'; 
            }
        }
    }
?>

This code is completely functional and working, the thing is that I want to add more than one range so I did this:

$ban_ip_range = array('10.49.*.*','10.65.*.*');

But this one didn't work , it goes throught the two parts of the conditional and it shows :

"NO accessyou have access"

Any way of fixxing it?


Solution

  • Use a flag, toggle it when you find a match, evaluate it after the loop.

    $ban_ip_range = array('10.49.*.*','10.65.*.*');
    $user_ip = '10.65.1.2'; //$_SERVER['REMOTE_ADDR'];
    $access = true;
    
    if(!empty($ban_ip_range)) {
        foreach($ban_ip_range as $range) {
            $range = str_replace('*','(.*)', $range);
    
            if(preg_match('/'.$range.'/', $user_ip)) {
                $access = false;
                break;
            }
        }
    }
    
    if($access) {
        echo 'you have access'; 
    } else {
        echo 'NO access';
    }