file_put_contents ( "file", "data", LOCK_EX )
for writing (which means - aquire lock and write)
file_get_contents ( "file", LOCK_EX )
for reading (which means - aquire lock and then read)
will it throw exception? raise an error? block until lock is aquired? or at least - should it? is there a chance that php will behave like this one day?
EDIT: i know that it is possible to use rename - i'd like to know answer to this...
Since this answer is long, here's the summary: No,
file_get_contents()is not atomic as it does not respect advisory locks.
About file locks in PHP:
In PHP, while on a *nix platform, filesystem locking is advisory only. Per the docs (Emphasis mine):
So, as long as all of the processes that are accessing the file use this method of locking, you're fine.
However, if you're writing a static HTML file with a sane webserver, the lock will be ignored. In the middle of the write, if a request comes in, Apache will serve the partially written file. The locks will have no effect on the other process reading the lock.
The only real exception is if you use the special mount option of
-o mandon the filesystem to enable mandatory locking (but that's not really used much, and can have a performance penalty).
Have a read on File Locking for some more information. Namely the section under Unix:
So, in conclusion, using
LOCK_EXwill create an advisory lock on the file. Any attempt to read the file will block only if the reader respects and/or checks for the lock. If they do not, the lock will be ignored (since it can be).
Try it out. In one process:
And while it's sleeping, call this:
The output will be
To your other specific question, first off, there is no
file_get_contents. So you can't pass that in.
Now, looking at the source code, we can see the function
file_get_contentsdefined on line 521. There are no calls to the internal function
php_stream_lockas there are when you pass
file_put_contents('file', 'txt', LOCK_EX);defined on line 589 of the same file.
So, let's test it, shall we:
file2.phpreturns immediately. So no, it doesn't appear that
file_get_contentsrespects file locks at all...