Save the IP of the visitor in a text file, but how can I not save it again if it is already there and how to read it?

2

I used the answer to this question to save the IP in a text file: How to save the IP of who visited my site in a text file?

This is what I want to create a "like" button for students to enjoy those they think are the best teachers.

But how do you prevent a student who has already enjoyed short-

I figured that having a text file for each teacher, inside a folder, with the number of ips they enjoyed would be a solution. Could the database be too long or does it work?

I know I can use Facebook plug-ins, for example, but what if my site's colors do not match anything on the face, or if for example this system works on an intranet? Anyway I want to know the logic to achieve this goal.

    
asked by anonymous 11.09.2014 / 15:24

2 answers

2

As people have already commented in the comments, you'd better use something other than IP to mark the vote, but if you still want to check if an IP already voted, use something like:

$arquivo = "ips.txt";

function has_voted($ip) {
  // o método file retorna um array com cada linha do arquivo
  $rows = file($arquivo);

  // basta verificar se o ip do usuário já está gravado no arquivo.
  in_array($ip, $rows);
}

if (!has_voted($_SERVER['REMOTE_ADDR'])) {
  vota(); // seu método para votar

  // grava o ip do cara que acabou de votar no arquivo de ips
  // http://pt.stackoverflow.com/a/31970/2321
  $ip = $_SERVER['REMOTE_ADDR']  . "\n";
  file_put_contents($arquivo, $ip, FILE_APPEND | LOCK_EX);
}
    
11.09.2014 / 19:34
0

Some considerations:

a) Save your file as json, because you can always use it with other languages. It might look something like this:

{"ipss":["111.111.111.111","222.222.222.222"]}

and save as file_name.json. You can also use comma-separated values (CSV), but I prefer json, which I find more descriptive.

b) The more ips you have, the slower it will be and the execution of the function, because where we are going to act is a collection, then as the collection increases, more data we have to act. The databases are optimized for this.

c) I did not include opening and saving the file, as you already know how to do it.

function check_ip($novo_ip)
{
    $sip = NULL;

    //aqui abre o arquivo json
    $ips = '{"ipss":["111.111.111.111","222.222.222.222"]}';

    //verifica se o ip é válido
   if (!filter_var($novo_ip, FILTER_VALIDATE_IP)) 
        return "Não pode votar";

    //passa json para array
    $o = json_decode($ips,TRUE);

    //já votou, não pode votar mais
    if(is_array($o['ipss']) && in_array($novo_ip, $o['ipss']))
        return "Não pode votar";

     $o['ipss'][]="$novo_ip";

     //cria miolo do json
     foreach ($o['ipss'] as $value) 
     {

            $sip .='"'.$value."',";
    }

    //aqui eu coloquei return mas pode colocar para gravar o aquivo atualizado
    return '{"ipss":['.trim($sip,",").']}';

}
    
11.09.2014 / 19:28