Search code examples
phpduplicatespreg-split

how to stop duplicate values from being written to text file using 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."\n";

    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


Solution

  • $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);
    }