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.
– Bruno