Jump to content

Barring sites


grucker

Recommended Posts

I use the following:

<?php

$deny = array("111.222.333.255", "333.333.333.1", "24.101.36.6" );

if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {

  header("location: http://www.yourchoice.co.uk/");

  exit();

} ?>

 

To ban ip's however when I use 111.111.111.* including a wildcard it does nothing. I have tried double..  but to no avail. I do not understand ereg so any ideas?

Thanks

Link to comment
https://forums.phpfreaks.com/topic/202498-barring-sites/
Share on other sites

Hi there.  :)  If you want to block entire ranges of IP addresses (i.e. 111.222.333.* or 192.168.*.*) then you'd probably need to use regex.  I just gave this bit of code a go and it seems to work with the examples I've set in the $deny array:

 

<?php

// Set banned IPs and IP ranges - wildcard combinations should all work
$deny = array(
'111.222.333.444',
'111.222.333.*',
'222.*',
'333.444.*',
'444.*.555.*'
);

// Loop through each denied entry
foreach ($deny as $blockedIp) {
$blockedIp = preg_quote($blockedIp);   // Escape metachars
$blockedIp = str_replace('\*', '.*', $blockedIp);   // Relplace escaped * with .* to match multiple unknown chars
$regex = '/' . $blockedIp . '/U';   // Construct regex variable with 'ungreedy' mode on
if (preg_match($regex, $_SERVER['REMOTE_ADDR']) == 1) {
	header("location: http://www.yourchoice.co.uk/");
	exit();
}
}

?>

 

The downside to this method is that every check is now being done with regex, putting more resource use on the server than the in_array() method you were previously using.  If you anticipate using this a lot then I'd recommend seperating the checks for static banned IPs and wildcard range IPs with something like this:

 

<?php

// Set denied static IPs in here
$denyStatic = array(
'111.222.333.255',
'333.333.333.1',
);

// Set denied IP ranges in here
$denyRange = array(
'111.222.333.*',
'222.*',
'333.444.*',
'444.*.555.*'
);

// First to basic check against static list
if (in_array($_SERVER['REMOTE_ADDR'], $denyStatic)) {
   header("location: http://www.yourchoice.co.uk/");
   exit();
}

// Didn't find them in the static list?  Try the range list instead!
foreach ($denyRange as $blockedIp) {
$blockedIp = preg_quote($blockedIp);
$blockedIp = str_replace('\*', '.*', $blockedIp);
$regex = '/' . $blockedIp . '/U';
if (preg_match($regex, $_SERVER['REMOTE_ADDR']) == 1) {
	header("location: http://www.yourchoice.co.uk/");
	exit();
}
}

?>

 

Best of luck!  :)

Link to comment
https://forums.phpfreaks.com/topic/202498-barring-sites/#findComment-1061596
Share on other sites

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.