Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading