I have a json file. I am getting all the contents using file_get_contents and putting the content in a variable called $js. Then I am appending new data or maybe delete some data from the $js variable. Then I am overwriting the data to the json file using file_put_contents. But many user will use it.
Is there any way to synchronize it. Like when one user has used file_get_contents, until he overwrites it other users will have to wait. I am thinking something like semaphore. As far as I understand flock will not work since I am not opening the json file to read and write.
Yeah, semaphore should do the trick. Though this will require additional mechanism to queue incoming queries (the modifications to your json file) and this sounds potentially problematic with stateless programming.
You could try send the request again and again until you successfully modify the file, but this is bad. The way I see, it you could use multithreading (http://php.net/manual/en/intro.pthreads.php). One thread for managing the queres:
Second thread could be used to read the database or files (depending on the implementation) and modify your json file.