Forums

How to block IP range?

KD24 28 Nov, 2014
Hello,

this solution from the FAQ works very well.

But I couldn't find out how to block a range of IP adresses, for example: 66.249.90.1 up to 66.249.90.255?

What ever I tried, it didn't work ... What would be the right code?

thank you very much!
BNDragon 28 Nov, 2014
Hi KD24,

Isn't just set:
$banned_ips = array(
  '66.249.90.1',
  '66.249.90.255'
);

?

If the solution had worked, so this is all what you need I believe.

BN
KD24 28 Nov, 2014
No, this works as a collection of single IPs, so xxx.1 and xxx.255 are blocked, but not x.103 for example?!

I have tried '66.249.90.' (without the last data) and '66.249.90.0/8' as well, but it doesn't work.

It would be fine for Google spider & co, they always have little different IP ...
BNDragon 28 Nov, 2014
Answer
Hi KD24,

You right, I read the code wrong.

Use a function to create the array, some loops and you can do it. And if its just the last token, it will be easier because is just one loop.

<?php
$banned_ips = array();
function blockIp($startIp, $beginNumber, $endNumber)
{
$aux=array();
for($i=$beginNumber; $i<=$endNumber; $i++)
{
$ipBlock=$startIp.".".$i;
array_push($aux, $ipBlock);
}
return $aux;
}

$a='66.249.90';
$b=1;
$c=255;

$banned_ips = array_merge($banned_ips,  blockIp($a,$b,$c));

$ip_address = JRequest::getString( 'REMOTE_ADDR', '', 'server' );
if ( in_array($ip_address, $banned_ips) ) {
  $mainframe->redirect('index.php');
}
?>


I didn't test the code, so please test and debug if needed.
Note I use array_merge, because you can always add more ips like:
$banned_ips = array_merge($banned_ips,  blockIp($a,$b,$c));
$banned_ips = array_merge($banned_ips,  blockIp($d,$e,$f));
$banned_ips = array_merge($banned_ips,  blockIp($g,$h,$i));


hope it help,
BN
KD24 29 Nov, 2014
Perfect - thank you very much!

I will give a feedback after some days ...
KD24 02 Dec, 2014
It works very well so far ...

Thank you very much again!
BNDragon 02 Dec, 2014
Hi KD24,

I'm glad it worked for you.

cya,
BN
This topic is locked and no more replies can be posted.