如何使用php停止将重复值写入文本文件

如何使用php停止将重复值写入文本文件

问题描述:

i have a script that keeps reloading every 2 seconds, i made a code to create a txt file for each user IP and write the user name $name inside it. my problem is that everytime my script reloads it will write the $name of the specific IP again with every reload. the code is

 $ip_file = "ips/".$ip.".txt";

    $logip = fopen($ip_file,"a", 1);

    $name = $name."
";

    fwrite($logip, $name);  

    fclose($logip);

    return;

i need some way to verify if the name is already in the $ip_file and if it's there then not to write it again.

the idea behind this is to check if the same IP is used by more than one $name and then create a function to check all the $ip_file files for more than 1 $name and if so ban the violating $ip

thanks in advance

我有一个每2秒重新加载一次的脚本,我创建了一个代码来为每个用户IP创建一个txt文件 并在其中写入用户名 $ name code>。 我的问题是每次我的脚本重新加载它都会在每次重新加载时再次写入特定IP的 $ name code>。 代码是 p>

  $ ip_file  =“ips /".$ ip。”。txt“; 
 
 $ logip = fopen($ ip_file,”a“,1); 
 
 $ name = $ name。”
“; 
  
 fwrite($ logip,$ name);  
 
 fclose($ logip); 
 
 return; 
  code>  pre> 
 
 

我需要一些方法来验证名称是否已经在 $中 ip_file code>如果它在那里则不再写它。 p>

这背后的想法是检查是否有多个 $ name 然后创建一个函数来检查所有 $ ip_file code>文件,查看超过1个 $ name code>,如果是这样,禁止违反 $ ip code> p>

提前致谢 p> div>

$ip_file = "ips/".$ip.".txt";
$names = file_get_contents($ip_file); //read names into string
if(false === strpos($names,$name)) { //write name if it's not there already
    file_put_contents($ip_file,"$name
",FILE_APPEND);
}

Is this what you need?

<?php
$ip_file = "ips/".$ip.".txt";
$name = $name."
";

if (file_exists($ip_file)) {

    $valueInFile = file_get_contents($ip_file, true);

    if ($valueInFile == $name) {
       //Do something
    }
} else {
    $logip = fopen($ip_file,"a", 1);
    fwrite($logip, $name);  
    fclose($logip);
}
return;
?>

From: http://php.net/manual/en/function.file-exists.php