How to remove duplicate lines from txt using php?

Asked

Viewed 1,038 times

2

Well I’m creating a div which is updated every x seconds and I am displaying the users currently logged in, but my code is inserting every update the same record. Is there any way to delete repeated lines?

Follow the code I’m currently using:

<?php
$id_usuario = $_SESSION['user_id'];
$usuario = $_SESSION['user_name'];

//grava os dados no arquivo
$arquivo = fopen("usuariosonline.txt", "a");
fwrite($arquivo, "<p><img src='avatar/".$id_usuario.".jpg'/>".$usuario."</p>\n");
fclose($arquivo);

// pronto aki terminou de adicionar

$file_name = "usuariosonline.txt";

// transforma as linhas do arquivo em arrays
$lines = file($file_name);
// verifica se a linha não é um comentário (apenas se você queira adicionar comentários no file.txt)
foreach($lines as $key => $value){
    if(substr_count($lines, "#") == 0){
        $texts[] = trim($value);
    }
}

// retira as linhas duplicadas (se não for utilizar os comentário no file.txt, utilize a variável $lines)
array_unique($lines);

//abre o arquivo e o reescreve (se você não quer modificar o arquivo só ignora os códigos abaixo)
$file = fopen($file_name, "w");
fwrite($file, implode("\n", $texts));
fclose($file);

include('usuariosonline.txt');
?>

Still appeared the Warning:

Warning: substr_count() expects Parameter 1 to be string, array Given in line 19

  • Now the question became more objective. Note: this -1 was not mine, since you improved the question.

  • You can set to generate a cookie when the user logs in. Then you set to only re-enter if the cookie no longer exists. If you want the code, you can talk and change your topic by saying that you would also like this code to avoid confusion

  • Boy as to cookies I do not understand anything, but I have this doubt also in php, I create another question better? what question should I ask in this case?

  • You would only set a cookie when the user enters the page for the first time. So you could put to write his name in the file of online users only once. You can also set a time for this cookie to expire. It’s very simple. I recommended to change the topic, because anything that is not in agreement here they already give negative vote and are filling the bag.

  • I will try to create a new question, as the answers I’m on hj even made a vent on one of the issues that posted more worthwhile

  • 2

    @Victoreyer I think you should rethink your words. Here is no place for mess. If you do not like how it works, you are not required to use. If you have any constructive criticism or suggestion, do it on [meta] and the community will say or disagree with you. As for the issue of the question, it ends up disturbing the answer that has already been posted. The issues should be elaborated properly, to avoid this kind of thing.

  • I talked about that kind of answer too

  • 1

    @Victoreyer when you say "they already vote negative" you are excluding yourself. The community is all of us, you included :) If there are injustices sends a warning to moderation. If we separate between "we" and "they" we will all learn less about programming.

Show 3 more comments

1 answer

1

Searching found this post forum

and really is very simplicado the way, summarizing

// ler no formato de array
$list = file('file.txt');

// array unique remove as arrays(linhas) duplicadas
 $list = array_unique($list);

//  escreve de volta no arquivo
file_put_contents('uniques.txt', implode('', $list));

my complete code was like this

            <?php
    $id_usuario = $_SESSION['user_id'];
    $usuario = $_SESSION['user_name'];

        //grava os dados no arquivo
        $arquivo = fopen("usuariosonline.txt", "a");

        if (flock($fp, LOCK_EX)) { // faca um lock exclusivo
        fwrite($arquivo, "<p><img src='avatar/".$id_usuario.".jpg'/>".$usuario."</p>\n");
        flock($fp, LOCK_UN); // libera o lock
        } else {
        echo "Não pude travar o arquivo !";
    }

        fclose($arquivo);


    $list = file('usuariosonline.txt');


    $list = array_unique($list);


    file_put_contents('usuariosonline.txt', implode('', $list));

        include('usuariosonline.txt');
    ?>
  • if you have any idea of simplicting more is always welcome

  • 1

    The ideal would be not to put the data in the file, instead of eliminating the duplicates. It would be better if you read the file before, and instead of using Unique, try to locate the user. If it already exists, you don’t even save. Another problem of your solution is that if two different users access simultaneously, one of them will not be recorded. You would have to give one lock file before use. In short: 1 lock in the file, 2 le file. 3 see if user is already there. 4 if it is not, add and write, 5 undo the lock. http://php.net/manual/en/function.flock.php

  • Note that array_unique() preserves the keys of the array. It could use array_values() after array_unique

Browser other questions tagged

You are not signed in. Login or sign up in order to post.