php - 使用php和mysql有效禁止IP?

标签 php mysql ip

CREATE TABLE `banned_ip` (
  `id` INT( 25 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , 
  `ip` VARCHAR( 25 ) NOT NULL , 
  `reason` TEXT NOT NULL )

Config.php

    <?php
// config
$config['host'] = "localhost"; // host name of your mysql server
$config['user'] = "username"; // your mysql username
$config['pass'] = "password"; // your mysql password
$config['db'] = "database"; // the database your table is in.

// the @ sign is an error supressor, meaning we can use our own error messages, this connects and selects db
@mysql_connect("$config[host]","$config[user]","$config[pass]") 
    or die("There was an error connecting to the database, MySql said:<br />".mysql_error()."");
@mysql_select_db("$config[db]") 
    or die("There was an error connecting to the database, MySql said:<br />".mysql_error()."");
?>

Ban.php

<?php 
include("connect.php"); 
$ip = $_SERVER['REMOTE_ADDR']; 
$find_ip = mysql_query("SELECT * FROM banned_ip WHERE ip='$ip'"); 
$ban = mysql_fetch_array($find_ip); 
if($ip == $ban['ip']){ 
    die("You are banned from this site!");
else {
    echo "Your Were not Banned";
    $sql = "INSERT INTO user(ip) VALUES('$ip')";
} 
?>

我正在做的是检查我的数据库中的 ip 是否被禁止。如果没有被禁止,则向他显示消息“您没有被禁止”并禁止他。

将他的 IP 存储在数据库中。然后,如果他再次出现在网站上,将会显示“您已被禁止访问该网站!”

这样,我只允许每个 IP 访问我的内容一次。这个脚本足够高效吗?这个脚本不适合我。它没有禁止我的 IP,而是不断向我显示我的内容。

最佳答案

显然您正在使用不同的表。您对banned_ip进行选择查询,以检查该IP是否被禁止。但如果他没有被禁止,你尝试插入到用户表中。这样您就可以记下所有被禁止的 IP,但不会选择它们。

此外,当您查询数据库时,执行 SELECT * 是不好的行为。仅选择您需要的值(在这种情况下,什么都不重要,因为您检查他是否找到了 ip 的行)。

从来没有 100% 可靠的方法来阻止未登录的用户访问内容。如果您禁止一个 IP,您可能会同时禁止多个人(例如学校)。使用 cookie(以及 session )效率不够,因为 cookie 可以被删除。

<?php 
include("connect.php"); 
$ip = $_SERVER['REMOTE_ADDR']; 
$find_ip = mysql_query("SELECT ip FROM banned_ip WHERE ip='$ip'"); 
$ban = mysql_fetch_array($find_ip); 
if($ip == $ban['ip']){ 
    die("You are banned from this site!");
else {
    echo "Your Were not Banned";
    $sql = "INSERT INTO banned_ip (ip) VALUES('$ip')";
} 
?>

关于php - 使用php和mysql有效禁止IP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10470517/

相关文章:

MySQL日期格式DD/MM/YYYY选择查询?

javascript - 捕获网站访问者 ISP 主机地址和 IP 地址

php - MySQL查询返回奇怪的错误

php - 错误,在mysql中使用多个WHERE

php - 使用curl加载xsl页面返回实际的基数错误

php - 哪种数据库和语言更擅长处理 Unicode?

mysql - Where 子句未从表中提取正确的数据

camera - ONVIF : How to form the device web service address from the IP address of an NVT

c# - 将 IP 地址(整数)解析为名称

php - 使用 AJAX 将表单数组作为 POST 数组发送到 PHP