I have a PHP script that opens an XML document, gets the DOM and modifies it, and then overwrites the original document.
As I understand it, PHP calls are made asynchronously, so multiple users could be accessing the document at the same time and then saving to it with the second save overwriting the first.
I need this not to be the case. I can't use flock() since that only applies to the current process, so how can I accomplish this?
Add a comment
|
2 Answers
Actually, flock() doesn't only apply to the current process:
http://php.net/manual/en/function.flock.php
It does use the local filesystem, though, which may become an issue if you're using load-balanced webservers. Also, in order for flock to work you have to make sure that any other processes which may be "competing" for the file are also using flock, otherwise the processes will "step" on each other.
2 Comments
ghoti
This question about flock() timeouts is also interesting.
ethan.roday
Huh. Regarding different processes, that's not what W3 said (www.w3schools.com/php/func_filesystem_flock.asp)...although I guess their information might be a bit outdated. In any case, the flock() page in the Manual mentions that you need a file handle to lock on (I didn't have one since I was using the DOM), so I created a file called xml.lock that the PHP script opened and locked before trying to access the XML file. That worked perfectly.
Lock the file.
Create an empty file (e.g. xml.lock) to indicate that the xml is being opened by other process. Remove the empty file after finish modifying the xml.
1 Comment
ghoti
How is this better than just flocking the original XML document? And how does it handle the race condition in which two competing processes check to see whether
xml.lock exists, neither sees the file, so both try to create it?