Reputation: 105
I want to block some hostnames and ips from accessing my website, I use this codde to =block only one hostname or ip:
<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$ipz = $_SERVER['REMOTE_ADDR'];
if ($hostname === "blocked hostname" || $ipz == "blokced ip" ){
echo "redirect to some url";
}
else {
echo "show site content";
}
?>
But I have a long list hof hostnames and IPs to be blocked, I want to add all those bad IPs and hostnames I have in a separated file, and then check if the visitors hostname or IP is on that list or not. how can I do that and keep to site loading fast ?
Thanks
Upvotes: 2
Views: 1903
Reputation: 37004
First way, put all your ip in a single file, separated by a newline. Then, you'll do :
$ips = file("ips.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
if (in_array($hostname, $ips) || (in_array($ipz, $ips)) {
// redirect to some content for banned guyz
die();
}
// real things
If you need more info about file() flags, you can read this.
For security reasons, you may put your "ips.txt" file in a folder unavailable from the outside.
Second way, you have a sql table where all ips are stored :
require_once("config.php");
$dbh = new PDO("mysql:host={$host};dbname={$base}", $user, $password);
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$ipz = $_SERVER['REMOTE_ADDR'];
$sth = $dbh->prepare("select count(*) from banned_ips where ip IN (?, ?)");
$sth->execute(array($hostname, $ipz));
$count = $sth->fetchColumn();
if ($count > 0) {
// do some stuffs with banned user
die();
}
// do some stuffs with normal users
Upvotes: 2
Reputation: 419
I actually just implemented this feature last week into one of my sites. I have a MySQL Table with an IP column, and a reason column so both the user can see why their IP is banned, and whoever is able to edit/view the list.
$query = 'SELECT * FROM banned_ips';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$bannedips = array($row['ip']);
};
$ip=$_SERVER['REMOTE_ADDR'];
if (in_array($ip, $bannedips))
{
header('Location: some url');
};
Upvotes: -1