0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
odbhut.shei.chhele
  • 5,834
  • 16
  • 69
  • 109

1 Answers1

1

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.

Dawid O
  • 6,091
  • 7
  • 28
  • 36
  • I am really sorry, but the entire thing went above my head. Could you further explain? – odbhut.shei.chhele Sep 11 '14 at 23:27
  • 1
    The idea is simple. Try implementing a semaphore: http://php.net/manual/en/book.sem.php. However, you also need to consider how what happens to the users when they can't access the file. Do you send them an error? Constantly refresh the page to gain the access? What will happen if somebody gains the access and then never gives it back? This is a big bottle neck in your system. If the user has to have the latest version of the file to edit, then threads are useless. If however, you could extract the desired change, then they might be of some help. – Dawid O Sep 12 '14 at 09:40