PHP - Create .TXT file with Visitors' IP Log [duplicate]

-1

I have the following link:

<a target='_blank' class='btn-primary' href='exemplo/1/'> Clique Aqui </a>

I need every time the page containing this link is accessed by a different visitor ( IP ), change the link number.

  

I think it would be interesting to create a .txt file containing the numbers of each IP and the number that each IP will be responsible for.

Example ( numbers.txt ):

123.456.789.00 - 1
321.543.765.99 - 2
543.210.456.22 - 3
435.647.533.33 - 4

And so on ...

  

I need to be verified if the IP of the visitor is already in this list, if it is it takes the number that is responsible for this IP and places the link, if it is not, then the new IP is added in the list and added the number that it will be responsible and then placed on the link, thus:

Example: Visitor has an IP 321.543.765.99 that was responsible for the number 2 .

Then you will see:

<a target='_blank' class='btn-primary' href='exemplo/2/'> Clique Aqui </a>
  

Is it possible to do this? How?

    
asked by anonymous 26.11.2016 / 05:26

1 answer

1

A scope of how you can deploy:

The test txt file looks like this

123.456.789.00 - 1
321.543.765.99 - 2
543.210.456.22 - 3
435.647.533.33 - 4

This is the routine:

<?php

$ip = '123.123.123.123';
$file = __DIR__.DIRECTORY_SEPARATOR.'tmp6.txt';
$content = file_get_contents($file);

$number = null;
$ip_len = strlen($ip) + 3;
$pos = strpos($content, $ip);

if ($pos !== false) {
    $part1 = substr($content, $pos + $ip_len);
    //echo $part1.'<br> len '.strlen($part1);
    //var_dump(strpos($part1, PHP_EOL));
    $number = substr($part1, 0, strpos($part1, PHP_EOL));
} else {
    $pos = strrpos($content, ' ');
    //var_dump($pos);
    $number = trim(substr($content, $pos)) + 1;
    $fs = fopen($file, 'a');
    fwrite($fs, $ip.' - '.$number.PHP_EOL);
    fclose($fs);
}

echo 'number '.$number;

Be aware that you can optimize, and the above script is inconsistent with potential crashes.

The script relies on the value of PHP_EOL as a line break character. In certain environments or situations it may be incompatible. Example txt can be saved with various line breaks. To minimize this problem, make sure you always save with the same formatting pattern.

Still, consider using SQLite or other logic to simplify this problem that might not even exist.

One suggestion is to just encode the IP and use this encoded string in place of the number to form the URL. In that case you do not have to do anything with this junk with txt, sqlite, nothing at all. A single line would solve

echo md5($ip);

This is how I would solve the problem, to avoid having to give all this back that seems unnecessary. Finally, the decision is for each one.

    
26.11.2016 / 05:54