1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
-1

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

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.