首页 > 解决方案 > 仅重定向一次并保存访问者 ip

问题描述

代码工作正常,但是当它存储了 200 个 ip 时,它会自动删除它,我希望它不删除任何 ip,除非我手动删除它们

$ipfile = "ips.txt";
$ips = explode("\n",file_get_contents($ipfile));
$isban = 0;
foreach($ips as $ip) {
    $ip = explode(" ",$ip,2);
    if($_SERVER['REMOTE_ADDR'] == $ip['0']) {
        $isban++; 
    }
}
if(!empty($isban))
{
    die("IP IS BANNED!");
}
else
{
    $ips[] = $_SERVER['REMOTE_ADDR']." ".date("d/m/y");
    $ips = implode("\n",$ips);
    file_put_contents($ipfile,$ips);
    header('Content-Type: text/html; charset=UTF-8');
    header('Location: http://www.google.com/');
    exit;
}

我希望它存储所有 ip 而不会删除它,我是否必须使用数据库以便它可以更好地工作或有人带给我的一些解决方案都没有关系。

标签: phparrays

解决方案


使用数据库要容易得多。这是示例。

在 Mysql 中:

CREATE DATABASE addr;
USE addr;

CREATE TABLE ips (
  id INT AUTO_INCREMENT PRIMARY KEY,
  ip VARCHAR(45),
  visit_timestamp TIMESTAMP DEFAULT now()
);

在 PHP 中:

$conn = new mysqli('localhost','username','password','addr');

$remote_ip = $_SERVER['REMOTE_ADDR'];

$query2 = "SELECT * FROM ips WHERE ip = '$remote_ip'";

$isban = mysqli_num_rows($conn ->query($query2));


if($isban > 0){
    die("IP IS BANNED!");
}
else{

    $query = "INSERT INTO ips (ip) VALUE ('$remote_ip')";

    $conn->query($query);

    header('Content-Type: text/html; charset=UTF-8');
    header('Location: http://www.google.com/');
    exit;
}

推荐阅读