Check ip, register in array, convert to json and write to file

Asked

Viewed 134 times

3

Guys, I’m having a problem. I have a php script that opens a json file, decodes it with json_decode and then checks if the json object has the current visitor’s ip, if it’s left behind, but, if it isn’t, registers it in an array to encode in json and write to the json file.

My question is that I am not being able to check each ip and if I do not have ip register in the array only once. I’m using for and it repeats every action of the IF.

See the iteration code:

for ($i = 0; $i < $total_visitors; $i++){
    $ip = $decoded_json_stats[$i]->ip;

    if ($ip == $visitor_ip) {
        echo "tem cadastrado<br>";
    } else {
        echo "não tem cadastrado<br>";
    }
}

Where’s the problem? I tried with foreach but the already registered ip was re-registered. See the complete code of my script so far.

<?php

/* Pegar o ip do visitante e cadastra no arquivo de estatisticas
*/
$visitor_ip = $_SERVER["REMOTE_ADDR"];

$fstats = file_get_contents("stats.json");
$decoded_json_stats = json_decode($fstats);
$decoded_json_to_array = json_decode($fstats, true);
$total_visitors = count($decoded_json_stats);

$a = "127.0.0.4";

for ($i = 0; $i < $total_visitors; $i++){
    $ip = $decoded_json_stats[$i]->ip;

    if ($ip == $visitor_ip) {
        echo "tem cadastrado<br>";
    } else {
        $new_visitor_array = array("ip" => $visitor_ip);
        array_push($decoded_json_to_array, $new_visitor_array);

        $new_json = json_encode($decoded_json_to_array);

        $file = fopen("stats.json", "w");
        fwrite($file, $new_json);
        fclose($file);
        return false;
    }
}
?>

I have a file called Stats.json which is where the registered ips will be. See how it is at the moment:

[{"ip":"127.0.0.2"},{"ip":"127.0.0.1"},{"ip":"127.0.0.4"}]

The script is in English at my preference.

Thank you!

  • No, check if a certain ip already has in the object and if you have not registered in the array and then turn into json object to register in the file.

2 answers

2


Let’s go through the json objects and see if any of them match the visitor’s ip ($new_ip, in this case), in which case the $jsonRaw will come from the file in your case, ex:

$jsonRaw = '[{"ip":"127.0.0.6"},{"ip":"127.0.0.1"},{"ip":"127.0.0.4"},{"ip":"192.168.1.72"},{"ip":"192.168.1.73"}]';
$jsonDeco = json_decode($jsonRaw);
$new_ip = '17.0.0.1';
$found = false;
foreach($jsonDeco as $ip) {
    if($new_ip == $ip->ip) {
        echo 'tem cadastrado ' .$ip->ip. '<br>';
        $found = true;
        break;
    }
}
if(!$found) {
    $jsonDeco[] = array('ip' => $new_ip);
}
$new_json = json_encode($jsonDeco);
$file = fopen("stats.json", "w");
fwrite($file, $new_json);
fclose($file);
  • What would $Unique be? fwrite($file, $Unique);

  • @Bruno, that was another attempt... Forget it, I’m sorry I made the first way as if you wanted to remove duplicates, and that var ended up by mistake

  • Dude here worked perfectly well! Replace jsonRaw with the call in the Stats.json file and ta everything ok! Thanks

  • Ready! I signaled the answer

  • (: @Bruno, welcome to Stack overflow

  • Thank you! =) !!

Show 1 more comment

2

You can use the function array_filter to check if the new IP already appears in an array of registered IP’s;

$jsonRaw = '[{"ip":"127.0.0.6"},{"ip":"127.0.0.1"},{"ip":"127.0.0.4"},{"ip":"192.168.1.72"},{"ip":"192.168.1.73"}]';
$jsonDeco = json_decode($jsonRaw, true); # Converte o json para array

$new_ip = '127.0.0.6';

$has_ip = array_filter($jsonDeco, function($indice) use ($new_ip) {
    return $indice['ip'] == $new_ip;
});

if (empty($has_ip)) {
    array_push($jsonDeco, ['ip' => $new_ip]);
    ... # grava o array $jsonDeco após realizar o json_encode no arquivo
}

The array_filter will return an array with the ips found in the ips list, so you can check whether it is empty or not, if so the IP has not yet been registered.

  • Good answer, I thought about it too but I think if it’s a json with thousands of data we would have to go through them all, even if we found the event in the first instance we would have to go through the rest unnecessarily. + 1, is still a good solution

  • Thanks but Miguel’s solution has already served me!

Browser other questions tagged

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