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/