phpgeolocationgeotargetting

block hostnames and IPs with php


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


Solution

  • 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