phpjsonsemaphoresynchronizeflock

Synchronize file_get_contents and file_put_contents functions using PHP


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.


Solution

  • 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:

    1. you could use a database to insert incoming queries (use engine that is fast on INSERT/DELETE)
    2. or you could create a file with a query save it (that should be fast enough)

    Second thread could be used to read the database or files (depending on the implementation) and modify your json file.