Personally I'm having a problem. I have a script in php that opens a json file, decodes it with json_decode and then checks to see if the json object exists in the current visitor's ip, if it has it, but if it does not, it registers in an array to encode json and save in the json file.
My question is that I am not 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 is the problem? I already tried with foreach but the ip already registered was registered again. See the full 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. Here's how it's at the moment:
[{"ip":"127.0.0.2"},{"ip":"127.0.0.1"},{"ip":"127.0.0.4"}]
The script is in English for my preference.
Thank you!