PHP banning IP address to block user from accessing website

时间:2017-06-12 17:03:17

标签: php html

I want to ban IP address to block user from accessing the website. I have this code for banning IP address.

$deny = array("111.111.111", "222.222.222", "333.333.333");
if(in_array ($_SERVER['REMOTE_ADDR'], $deny)){
   die("Your IP has been banned from accessing the website");
}

Now if I have comma separated values in database I can easily code this out by fetching the data and exploding it. But I have stored it as one IP every row. Now how can I make check that in array here?

3 个答案:

答案 0 :(得分:2)

您不需要数组或循环或其他任何东西来实现此目的。只需尝试从表中选择IP地址即可。如果它不存在,您就知道IP未被禁止。

<?php
    $ip = $_SERVER['REMOTE_ADDR'];
    $sql = "SELECT * FROM banned_ips WHERE ip_address = '$ip'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        die("Your IP has been banned from accessing the website");
    }
?>

答案 1 :(得分:-1)

You can get ip address through $_SERVER[REMOTE_ADDR] and then get data from the table with group_concat clause , if the ip address present into array then block the access else allowed.

$query = "select group_concat('ipaddress') bannedAddress from iptable limit 0,1";
$result = mysql_fetch_array(mysql_query($query));


if(in_array ($_SERVER['REMOTE_ADDR'], $result[0]['bannedAddress'])){
     die("Your IP has been banned from accessing the website");
}

答案 2 :(得分:-1)

你可以通过选择该表中的每一行然后将其推入数组中来实现这一点(这里我使用的是mysqli,但它也适用于普通的mysql。你只需要稍微修改一下代码):

$deny = array();
$sql = "SELECT * FROM `banned_addresses`";
$result = $mysqli->query($sql);

while ($row = $result->fetch_assoc()) {
    array_push($deny, $row["address"];
}

if(in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
    die("Your IP has been banned from accessing the website");
}

但是有更好的方法来禁止IP。例如,您可以检查表中是否存在该IP地址的条目。这要快得多:

$sql = "SELECT * FROM `banned_addresses`";
$result = $mysqli->query($sql);

if(mysql_fetch_array($result) !== false) {
    die("Your IP has been banned from accessing the website");
}

对于许多服务器,还有一些方法可以直接禁用IP地址。对于Apache,有this指南。