Efficiently Banning IPs Using php and mysql?

2019-08-09 07:10发布

问题:

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')";
} 
?>

What I am doing is check my database for a ip , if it is banned or not. IF not banned, Showing him message "Your Were not Banned" and banning him.

Storing his ip in database. And then if he comes again on site, is will be show "You are banned from this site!"

By this i am giving each ip only one time access to my content. Is this script efficeint enough? This script is not working for me. It is not banning my ip , instead it keeps showing me my content.

回答1:

You are working with different tables obviously. You do a select query for banned_ip, to check if the IP is banned. But if he is not banned, you try to insert into the user table. This way you do note down all banned IPs, but you don't select them.

Also, when you query the database, it's bad behaviour to do SELECT *. Select only the values you need (in this case it doesn't even matter what, since you check if he finds an row for the ip).

There's never a 100% sure way to prevent non-logged-in users from accessing content. If you ban an IP, you might ban several persons at once (like schools). Using cookies (and also Sessions) is not efficient enough, since the cookie can be deleted.

<?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 mysql ip