How do I save the IP of the person who visited my site to a text file?

Asked

Viewed 2,690 times

2

I’m using the code below, but only writes "::1" to the file.

<?php 
$arquivo = "ips.txt";
$file = fopen($arquivo,"a"); 
$string = $_SERVER['REMOTE_ADDR']  . "\n";
$fp = fwrite($file,$string);
fclose($file);
?>

Is it because I’m on localhost?

  • 2

    Depending on your server’s settings it may even be. It may seem silly, but echo $_SERVER['REMOTE_ADDR'] returns the same thing?

  • 1

    You can test if you have another device on the network. It can even be your cell phone. Enter the page you are doing and make an echo as Bruno said.

  • Yes, returns "::1" as well.

  • 3

    ::1 is the localhost Ipv6

  • 1

    Have you considered using http://www.google.com/intl/pt-BR_ALL/analytics/

  • @Alexschmitt I know, but right now I need that knowledge.

  • I tested on a free host the code and it works. I followed @chambelix’s reply, but every time I update the page the same ip is recorded again. How to record only if you’re not already there?

  • If the user is using proxy, you would have to match some checks with, HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, however, they can be easily manipulated while REMOTE_ADDR cannot. Take into account that some programs provide a new IP for "anonymous" browsing, and in this case the IP nay would be the real IP of the user even using REMOTE_ADDR.

  • Truth, for question of identification is uncertain, however for statistical purposes should serve.

Show 4 more comments

1 answer

3


using the code placed in question ... I just remembered this way...

<?php
    $arquivo = "ips.txt";
    $string = $_SERVER['REMOTE_ADDR']  . "\n";
    // ao usar FILE_APPEND para adicionar ao ficheiro estamos a colocar no fim do mesmo
    // e com o LOCK_EX trata das gravações concurrentes que podem acontecer
    file_put_contents($arquivo, $string, FILE_APPEND | LOCK_EX);
?>

::1 is the notation Ipv6 for 127.0.0.1

  • I tested it on a free host and the codes and work. I followed your answer, but every time I update the page the same ip is recorded again. How to record only if you’re not already there?

  • 2

    I recommend the use of a database. Otherwise you will have to read the file and search for its IP, clearly a worse solution.

  • I’ll do it myself, but I need to know how to work files for other things.

  • How I would read?

Browser other questions tagged

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