Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用php阻止重复值写入文本文件_Php_Duplicates_Preg Split - Fatal编程技术网

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

如何使用php阻止重复值写入文本文件,php,duplicates,preg-split,Php,Duplicates,Preg Split,我有一个脚本,它每2秒就重新加载一次,我编写了一个代码,为每个用户IP创建一个txt文件,并在其中写入用户名$name。我的问题是,每次脚本重新加载时,它都会在每次重新加载时再次写入特定IP的$name。 代码是 $ip_file = "ips/".$ip.".txt"; $logip = fopen($ip_file,"a", 1); $name = $name."\n"; fwrite($logip, $name); fclose($logip)

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

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

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

    $name = $name."\n";

    fwrite($logip, $name);  

    fclose($logip);

    return;
我需要一些方法来验证名称是否已经在
$ip_文件中,如果它在那里,那么就不要再写了

这背后的想法是检查同一IP是否被多个
$name
使用,然后创建一个函数来检查所有
$IP\u文件
中超过1个
$name
的文件,如果是,则禁止违反
$IP

提前谢谢你这是你需要的吗

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

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;
?>

发件人:

这个答案与重复值无关。我已经在写filename.txt了,所以我知道它存在,我需要验证它里面的数据。对不起,那么可能是“a”参数?不是从附录中吗?+1这比我的答案好,我不太理解主要的观点,这正是我希望它的工作方式:)我想我现在需要一种方法,使用preg_split检查文件是否有多个名称来执行一个功能如何添加代码来检查
$name
文件中是否有多个
$ip_
来执行另一个命令?谢谢你advance@GuestofHonor
如果(count(file($ip_file))>1)
@FuzzyTree,该命令不起作用,因为它禁止了我的所有用户:)命令计数
$ip_file
,而不是文件中的
$name
$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\n",FILE_APPEND);
}