Block Specific Ip Block from My Website in PHP

Block specific IP block from my website in PHP

Try strpos()

if(strpos($_SERVER['REMOTE_ADDR'], "89.95") === 0)
{
die();
}

If you notice, the === operator makes sure that the 89.95 is at the beginning of the IP address. This means that you can specify as much of the IP address as you want, and it will block no matter what numbers come after it.

For instance, all of these will be blocked:

89.95 -> 89.95.12.34, 89.95.1234.1, 89.95.1.1

89.95.6 -> 89.95.65.34, 89.95.61.1, 89.95.6987

(some of those aren't valid IP addresses though)

php blocking visitors based on text list of ips

You could build up an array of the banned IP's from the file (you are just overwriting the last one in your code, use $bannedip[] to add it to a list) and then use in_array() to check the users IP against this list...

$link_file = "bannedips.dat";
$lines = file($link_file);
$bannedip = []; // Create start array
foreach($lines as $line){
if(!empty($line)){
$line_array = explode(',', $line);
$bannedip[] = trim(trim(strip_tags($line_array[0]), "\x00..\x1F"));
}
}
if(in_array($IP, $bannedip )) {
$line = date('Y-m-d H:i:s') . " - <b>$IP</b><br>\n";
file_put_contents('403.shtml', $line . PHP_EOL, FILE_APPEND);
header('Location: 403.shtml');
die();
}

There may be a tidier way of dealing with the input file, but without knowing the format it's difficult to say, so I've left your code as it was.

Update:

If you banned IP file is just a list of IP addresses, you could replace the load and foreach with...

$bannedip = file($link_file, FILE_IGNORE_NEW_LINES);
$bannedip = array_filter($bannedip);

Update2:
As you seem to have sorted this out yourself, but posted a sample of the actual file format you have, thought I would add how it could be done...

$IP= "31.130.4.241";
$link_file = "bannedips.dat";
$bannedip = file($link_file, FILE_IGNORE_NEW_LINES);
$bannedip = array_map("str_getcsv", $bannedip);
$bannedip = array_column($bannedip, null, 0);
if(isset($bannedip[$IP])) {
$line = date('Y-m-d H:i:s') . " - <b>{$bannedip[$IP][0]}</b> - {$bannedip[$IP][1]} - {$bannedip[$IP][2]}<br>\n";
file_put_contents('403.shtml', $line . PHP_EOL, FILE_APPEND);
header('Location: 403.shtml');
die();
}

how do I IP Block someone who is dosing me php or html

If you are running apache and are on shared hosting (no access to firewall on the server), then I would opt for htaccess. This would go in a file named .htaccess in your web directory:

Order Deny,Allow
Deny from 10.10.10.10
Deny from 20.20.20.20

Obviously use the IP addresses you want to block instead of these example ones and use a line for each IP



Related Topics



Leave a reply



Submit