How to read the information and after, write it to a text file?
I try to do it as described in the following text, but apparently, a race condition is formed . Suppose if there are only two iterations in the loop, then this code will work well.
See:
File cahe.json is in the system and contains the original entry
{"count":"1", "count_1":"0"} We use variant A with two iterations for ($i=0; $i < 2; $i++) {
at the output we get a record in the file
{"count":"1", "count_1":"2"} We use variant B with a thousand iterations for ($i=0; $i < 1000; $i++) {
at the output we get a record in the file
{"count":"1", "count_1":"01"} instead
{"count":"1", "count_1":"1000"} We use the C variant with a thousand iterations for ($i=0; $i < 1000; $i++) { , but we change the initial value in the cahe.json file
with
{"count":"1", "count_1":"0"} on
{"count":"1", "count_1":"1000"} at the output we get a record in the file
{"count":"1", "count_1":"2000"} Use option D with a thousand iterations for ($i=0; $i < 1000; $i++) { and plus , remove a piece of code filesize(__DIR__.'/cahe.json') , replacing it with this one - '20000', let's say
at the output we get a record in the file
{"count":"1", "count_1":"1000"} //CODE
for ($i=0; $i < 1000; $i++) { //------------------------------------------------ $json_data; $contents = ''; $fp = fopen(__DIR__.'/cahe.json', "c+" ); if($fp == false){ //Π±ΡΠ»Π° ΠΎΡΠΈΠ±ΠΊΠ° var_dump("ΠΡΠ»Π° ΠΎΡΠΈΠ±ΠΊΠ° ΠΏΡΠΈ ΠΎΡΠΊΡΡΡΠΈΠΈ ΡΠ°ΠΉΠ»Π°"); }else{ if (flock($fp, LOCK_EX)) { // Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΠΌ ΡΠΊΡΠΊΠ»ΡΠ·ΠΈΠ²Π½ΡΡ Π±Π»ΠΎΠΊΠΈΡΠΎΠ²ΠΊΡ //------------------------------------------------ $contents = fread($fp, filesize(__DIR__.'/cahe.json')); $json_data = json_decode($contents, true); //------------------------------------------------ ftruncate($fp, 0); // ΠΎΡΠΈΡΠ°Π΅ΠΌ ΡΠ°ΠΉΠ» //ΠΏΠ΅ΡΠ΅ΠΌΠ΅ΡΠ°Π΅ΠΌ ΡΠ°ΠΉΠ»ΠΎΠ²ΡΠΉ ΡΠΊΠ°Π·Π°ΡΡΠ΅Π»Ρ Π² Π½Π°ΡΠ°Π»ΠΎ ΡΠ°ΠΉΠ»Π° fseek($fp, 0); //------------------------------------------------ $count_1 = $json_data['count_1'] + 1; $data = '{"count":"1", "count_1":"'.$count_1.'"}'; fwrite($fp, $data); //------------------------------------------------ fflush($fp); // ΠΎΡΠΈΡΠ°Π΅ΠΌ Π²ΡΠ²ΠΎΠ΄ ΠΏΠ΅ΡΠ΅Π΄ ΠΎΡΠΌΠ΅Π½ΠΎΠΉ Π±Π»ΠΎΠΊΠΈΡΠΎΠ²ΠΊΠΈ flock($fp, LOCK_UN); // ΠΎΡΠΏΠΈΡΠ°Π΅ΠΌ ΡΠ°ΠΉΠ» } else { var_dump("ΠΠ΅ ΡΠ΄Π°Π»ΠΎΡΡ ΠΏΠΎΠ»ΡΡΠΈΡΡ Π±Π»ΠΎΠΊΠΈΡΠΎΠ²ΠΊΡ!"); } fclose($fp); } //------------------------------------------------ }
file_get_contents()due tofile_get_contents(), competing streams are formed and there will be partial data loss at the output. - gilo1212textsimple. What is the difference? There all the samejsonis stored and not just text. - gilo1212